Rust Deserialization Lifetimes Problem : 'de must outlive 'a
Asked Answered
A

1

10

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?

Aback answered 21/11, 2022 at 10:7 Comment(0)
S
22

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.

Soursop answered 21/11, 2022 at 10:24 Comment(1)
Jinx, you're right your answer is better.Enate

© 2022 - 2024 — McMap. All rights reserved.