代码如下
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,person字段类型改成Cow<'a, Person>
之类的就好了。代码修改如下
use std::borrow::Cow;
use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)]
struct Person {
id: String,
name: String,
}
#[derive(Serialize, Deserialize)]
struct Msg<'a> {
id: String,
person: Cow<'a, Person>,
}
fn main() {
let person = Person {
id: "123".to_string(),
name: "Alice".to_string(),
};
let msg = Msg {
id: "456".to_string(),
person: Cow::Borrowed(&person),
};
let msg_str = serde_json::to_string(&msg).unwrap();
println!("Serialized Msg: {}", msg_str);
}
参考链接
标签:serde,string,Deserialize,Person,person,msg,序列化,id,rust From: https://www.cnblogs.com/ALXPS/p/18023272