Serde - generics implement Deserialize with lifetime

Hi, I want pass struct which implements Deserialize and a few traits more.

Why this code is not compiling

use serde::Deserialize;

pub struct Configuer<'de, T: Deserialize<'de>> {
    data: T,
}

Error: 'parameter de is never used'
Playground

The compiler is complaining that nothing in your struct depends on the deserializer’s lifetime, so it can’t be a generic parameter. There are a couple of different ways to get this to compile:

  • Move the Deserialize bound to your structure’s Deserialize implementation:
pub struct Configure<T> {
    data: T,
}

impl<'de, T> Deserialize<'de> for Configure<T> where T: Deserialize<'de> {
    fn deserialize<D:Deserializer<'de>>(_: D) -> Result<Self, D::Error> { todo!() }
}
  • Specify that T must be deserializable with any lifetime (i.e. it takes ownership of all the data it cares about):
pub struct Configure<T> where T: for<'de> Deserialize<'de> {
    data: T,
}

I’m not very familiar with Serde, so I don’t know which of these is most appropriate. Hopefully someone who is will chime in shortly.

1 Like

for<'de> Deserialize<'de> is a common enough pattern in Serde that there's even an "alias" for it: DeserializeOwned. Understanding deserializer lifetimes linked in the docs is also a good read.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.