代码如下
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct Person {
id: String,
name: String,
}
#[derive(Serialize, Deserialize)]
struct Msg<'a> {
id: String,
person: &'a Person,
}
fn main() {
let person = Person {
id: "123".to_string(),
name: "Alice".to_string(),
};
let msg = Msg {
id: "456".to_string(),
person: &person,
};
let msg_str = serde_json::to_string(&msg).unwrap();
println!("Serialized Msg: {}", msg_str);
}
报错如下
error[E0277]: the trait bound `&'a Person: Deserialize<'_>` is not satisfied
--> src/main.rs:2463:13
|
2463 | person: &'a Person,
| ^^^^^^^^^^ the trait `Deserialize<'_>` is not implemented for `&'a Person`
|
note: required by a bound in `next_element`
--> /home/alxps/.cargo/registry/src/index.crates.io-6f17d22bba15001f/serde-1.0.195/src/de/mod.rs:1726:12
|
1724 | fn next_element<T>(&mut self) -> Result<Option<T>, Self::Error>
| ------------ required by a bound in this associated function
1725 | where
1726 | T: Deserialize<'de>,
| ^^^^^^^^^^^^^^^^ required by this bound in `SeqAccess::next_element`
help: consider removing the leading `&`-reference
|
2463 - person: &'a Person,
2463 + person: Person,
|
我不想让msg有person所有权,也不想clone person,现在要自定义序列化实现trait,要怎么写?或者有没有其他方法
1
共 4 条评论, 1 页
评论区
写评论今天又进度, 原来Cow这么用的
谢谢
--
👇
aj3n: 序列化本来就没有问题,你手欠给
Msg
加了derive(Deserialize)
才报错了,删掉就好了;如果一定需要Deserialize, person字段类型改成
Cow<'a, Person>
之类的就好了;序列化本来就没有问题,你手欠给
Msg
加了derive(Deserialize)
才报错了,删掉就好了;如果一定需要Deserialize, person字段类型改成
Cow<'a, Person>
之类的就好了;不能用引用