Serde Deserialize Lifetime issue


#1

Hello,

I’m not understanding a snippet of code I’m trying to upgrade to Serde 1.0, and would appreciate help.

The old code using rustc_serialize was:

pub trait DTO: Encodable + Decodable {}

/// creates an object from a dto
pub trait FromDTO<D: DTO>: Sized {
    /// the from dto wrapper
    fn from_dto(dto: D) -> Result<Self, FromDTOError>;
}

Now I’m at this point:

pub trait DTO<'de>: Serialize + Deserialize<'de> {}

/// creates an object from a dto
pub trait FromDTO<D: DTO>: Sized {
    /// the from dto wrapper
    fn from_dto(dto: D) -> Result<Self, FromDTOError>;
}

And getting an error about DTO being undefined, I’ve tried adding it:

pub trait FromDTO<D: DTO<'dto>>: Sized {

But I’m being told that this is an "use of undeclared lifetime name 'dto"

I believe I have to add this lifetime somehow to FromDTO? Not sure how to add it to FromDTO given “<D: DTO<'dto>>”

This is probably a syntax issue? Thanks in advance!


#2
FromDTO<'dto, D:DTO<'dto>> 

should work?


#3

This is explained in more detail on the website under Understanding deserializer lifetimes but the short answer is it depends what you mean.

  • If D needs to be deserializable from some lifetime:

    trait DTO<'de>: Serialize + Deserialize<'de>;
    trait FromDTO<'de, D: DTO<'dto>>;
    
  • If D needs to be deserializable from any lifetime:

    trait DTO: Serialize + DeserializeOwned;
    trait FromDTO<D: DTO>;