Reputation: 1720
How does one nest serde-izable structs? I tried the simplest approach and the compiler complained about a lifetime not even in my program ('de
).
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct A<'a> {
symbol: &'a str,
}
#[derive(Serialize, Deserialize)]
enum B<'a> {
A(A<'a>),
}
Compiling rust_iex_parser v0.1.0 (...filename...)
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'de` due to conflicting requirements
--> src/test.rs:8:21
|
8 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'de` as defined here...
--> src/test.rs:8:21
|
8 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
note: ...so that the types are compatible
--> src/test.rs:8:21
|
8 | #[derive(Serialize, Deserialize)]
| ^^^^^^^^^^^
= note: expected `EnumAccess<'_>`
found `EnumAccess<'de>`
note: but, the lifetime must be valid for the lifetime `'a` as defined here...
--> src/test.rs:9:8
|
9 | enum B<'a> {
| ^^
note: ...so that the types are compatible
--> src/test.rs:10:7
|
10 | A(A<'a>),
| ^
= note: expected `<A<'a> as Deserialize<'_>>`
found `<A<'_> as Deserialize<'_>>`
= note: this error originates in the derive macro `Deserialize` (in Nightly builds, run with -Z macro-backtrace for more info)
Upvotes: 0
Views: 285
Reputation: 71300
For field types other than &[u8]
and &str
, that involves lifetimes, you have to annotate them with #[serde(borrow)]
. See Understanding deserializer lifetimes - Borrowing data in a derived impl:
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
struct A<'a> {
symbol: &'a str,
}
#[derive(Serialize, Deserialize)]
enum B<'a> {
#[serde(borrow)]
A(A<'a>),
}
Upvotes: 1