Reputation: 999
I have the following two structs for which I derive serde traits.
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Item<'a> {
pub id: &'a str,
pub name: &'a str
}
#[derive(Serialize, Deserialize)]
struct Set<'a> {
items: Vec<Item<'a>>
}
When I try to compile this, I am getting am getting the following error message to ensure that lifetime parameter 'de
from Deserialize
needs to outlife lifetime parameter 'a
:
15 | #[derive(Serialize, Deserialize)]
| ----------- lifetime `'de` defined here
16 | struct Set<'a> {
| -- lifetime `'a` defined here
17 | sets: Vec<Item<'a>>
| ^^^^ requires that `'de` must outlive `'a`
|
= help: consider adding the following bound: `'de: 'a`
But when I add the required bound as follows, I am getting an error message that 'de
is not used.
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
pub struct Item<'a> {
pub id: &'a str,
pub name: &'a str
}
#[derive(Serialize, Deserialize)]
struct Set<'a, 'de: 'a> {
items: Vec<Item<'a>>
}
16 | struct Set<'a, 'de: 'a> {
| ^^^ unused parameter
|
= help: consider removing `'de`, referring to it in a field, or using a marker such as `PhantomData`
How can I fix this?
Upvotes: 11
Views: 1664
Reputation: 601609
You need to add #[serde(borrow)]
to the sets
field:
#[derive(Serialize, Deserialize)]
struct Set<'a> {
#[serde(borrow)]
items: Vec<Item<'a>>,
}
This will bound the 'de
lifetime in the generated code on 'a
. Note that this happens implicitly for fields of type &str
or &[u8]
, but for anything else you need to expicitly request the trait bound.
Upvotes: 24