Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust Deserialization Lifetimes Problem : 'de must outlive 'a

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading