【问题标题】:error: type `&[str]` does not implement any method in scope named `encode`错误:类型 `&[str]` 未在名为 `encode` 的范围内实现任何方法
【发布时间】:2014-10-21 11:59:32
【问题描述】:

我正在尝试使用 JSON 接口编写一些 Rust。

我希望以下结构自动从 JSON 编码/解码:

#[deriving(Encodable)]
struct Joined<'a> {
    channel: &'a str,
    user: &'a str,
    users: &'a [str],
}

示例 JSON:

{
  "channel":"foo",
  "user":"bar",
  "users":[
    "bar",
    "baz",
    "quux"
  ]
}

我得到的错误是:

src/chat.rs:28:5: 28:21 error: type `&[str]` does not implement any method in scope named `encode`
src/chat.rs:28     users: &'a [str],
                   ^~~~~~~~~~~~~~~~
src/chat.rs:24:12: 24:21 note: in expansion of #[deriving(Encodable)]
src/chat.rs:28:5: 28:21 note: expansion site

我在 Rust 中的尝试是否可行,还是我误解了 Encodable 的本质?

【问题讨论】:

  • 对结构字段使用String,除非你有充分的理由使用切片。

标签: json rust


【解决方案1】:

&amp;[str] 是一种非常特殊的类型,当它编译时,你可能无法用它做任何事情:大多数字符串操作函数都是为 &amp;str 实现的,而不是 str 这是你的类型可能永远不会使用。

你的意思可能是users: &amp;'a [&amp;'a str],不是吗?

然而,这样的结构永远无法解码。如果你希望它是这样,它需要拥有它的内容,因此使用String 而不是&amp;strVec&lt;&gt; 而不是&amp;[],就像这样:

#[deriving(Encodable, Decodable)]
struct Joined {
    channel: String,
    user: String,
    users: Vec<String>,
}

【讨论】:

  • 我注意到您没有在成员类型中使用&amp;s。 users 字段会包含向量,还是只是对它的引用?
  • @chrisdew,是的,这就是重点。这里没有引用 (&amp;),所以是的,users 将包含向量。
  • @VladimirMatveev 这是否意味着 Joined 结构不再具有固定大小,因为它现在包含 Vector 的内容?这是个问题吗?
  • @chrisdew Vec 是一个固定大小的类型,它在堆内部处理它的内容。您的 Joined 结构保持固定大小,这没有问题。
  • @chrisdew,没有。该结构包含向量,但不包含其元素。向量本身只有三个指针大小的值。
【解决方案2】:

我已经做了一个答案,但我不确定它是否好(我是 Rust 新手)。

#[deriving(Encodable)]
struct Joined<'a> {
    channel: &'a str,
    user: &'a str,
    users: &'a Vec<&'a str>,
}

...

fn main() {
    let users = vec!["bar","baz","quux"];
    let joined = Joined{channel:"foo",user:"bar",users:&users};
    println!("{}", json::encode(&joined));

...

欢迎批评。


这也有效:(根据@Levans 的回答)

#[deriving(Encodable)]
struct Joined {
    channel: String,
    user: String,
    users: Vec<String>,
}

...

fn main() {
    let users = vec!["bar".to_string(),"baz".to_string(),"quux".to_string()];
    let joined = Joined{channel:"foo".to_string(),user:"bar".to_string(),users:users};
    println!("{}", json::encode(&joined));

...

认为不同之处在于,如果您将源 JSON 字符串保存在内存中(因为它可以被索引),第一个很好,但第二个会进行大量堆分配(但是让原始 JSON 字符串被释放)。

【讨论】:

  • 实际上,如果您尝试decode JSON(使用#[deriving(Decodable)]),您的第一个版本将无法工作:&amp;str 不实现可解码,因为由decode()必须自有。
  • @Levans 感谢您的解释。
猜你喜欢
  • 2015-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 2015-07-05
  • 2019-11-16
  • 2013-12-31
  • 1970-01-01
相关资源
最近更新 更多