serde::Deserialize lifetime frustration

I have a function read(…) which calls a restful endpoint, gets results and then uses serde_json::from_str() to deserialize to a vec of a struct which derives Deserialize. And it works, but i have a lot of different entities in the system, so i though that it would be trivial to write the function generic over the type…

The original signature looks like this:

fn read(/* params */) -> Result<Vec<Artifact>,Error> 

Internally, the results of the get are local to the function and they get passed in as a reference to serde:

 let v: Vec<Artifact> = serde_json::from_str(body.as_str())?;

This works
However when I change my signature to this:

fn read<'de,T>(/* params */) -> Result<Vec<T>,Error> 
   T: serde::Deserialize<'de> + Debug

And swap out the specific call for a generic one

 let v: Vec<T> = serde_json::from_str(body.as_str())?;

I get borrow checker complaint

  v = serde_json::from_str(body.as_str())?;
                               ^^^^ borrowed value does not live long enough
  |     - borrowed value only lives until here

How is it that this works in the non-generic case, and how would I go about fixing this?


Check out Understanding deserializer lifetimes which covers the meaning of 'de and how to use it.

1 Like

Thank you for rescuing my weekend!

DeserializedOwned… mystery solved

1 Like