0

We have a vector Vec<u8> that we want to deserialize to a type T. The minumum reproducing example we could come up with is

fn wrapper<'de, T>(vec: Vec<u8>) -> Result<T, serde_json::Error>
where
    T: serde::Deserialize<'de>,
{
    serde_json::from_slice::<'de, T>(&vec)
}

However, the compiler gives the following error:

error[E0597]: `vec` does not live long enough
   --> src/wrapper.rs:128:38
    |
124 | fn wrapper<'de, T>(vec: Vec<u8>) -> Result<T, serde_json::Error>
    |            --- lifetime `'de` defined here
...
128 |     serde_json::from_slice::<'de, T>(&vec)
    |     ---------------------------------^^^^-
    |     |                                |
    |     |                                borrowed value does not live long enough
    |     argument requires that `vec` is borrowed for `'de`
129 | }
    | - `vec` dropped here while still borrowed

Since we have full ownership of the vector and the type T doesn't have a reference to any of the original data (e.g. it could be a number or a String), I'm stumped as to what is causing this error.

I still get the same error with the following changes:

  • serde::Deserialize<'static>
  • serde::Deserialize<'de> + 'static
  • serde::Deserialize<'de> + 'de

1 Answers1

0

I found the solution with

fn wrapper<T>(vec: Vec<u8>) -> Result<T, serde_json::Error>
where
    T: for<'de> serde::Deserialize<'de>,
{
    serde_json::from_slice(&vec)
}

From Rust's documentation

Trait bounds may be higher ranked over lifetimes. These bounds specify a bound that is true for all lifetimes.

So the solution here was to have the trait being bound for all lifetimes, not a specific one. Including the lifetime of the function itself, which is the lifetime of vec.

  • 1
    This isn't wrong, but serde provides a trait that does this for you: `DeserializeOwned`. See explanation in the [serde docs for deserializer lifetimes](https://serde.rs/lifetimes.html#trait-bounds). – kmdreko Jul 28 '23 at 22:44
  • I didn't know about this trait! That's pretty sweet. I also really like their explanation of control by callee or caller. – mirandaconrado Jul 28 '23 at 22:52