[英]Error:(124, 9) error: method does not override or implement a method from a supertype
[英]error: type `&[str]` does not implement any method in scope named `encode`
我正在嘗試使用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
的本質?
&[str]
是一個非常特殊的類型,雖然它可以編譯,但是您可能將無法執行任何操作:大多數字符串操作函數都是針對&str
實現的,而不是str
(您可能永遠不會使用的類型)。
您的意思可能是users: &'a [&'a str]
,不是嗎?
但是,這樣的結構永遠無法解碼。 如果要這樣,它需要擁有其內容,因此使用String
代替&str
和Vec<>
代替&[]
,如下所示:
#[deriving(Encodable, Decodable)]
struct Joined {
channel: String,
user: String,
users: Vec<String>,
}
我已經回答了,但是我不確定它是否很好(我是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字符串)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.