Borrowed value does not live long enough! Why? and How to? Friends

pub fn variable_get<'de, T>(key: &str, default_value: T, conn: &PgConnection) -> T
where T: serde::Deserialize<'de> {
use schema::config::dsl::*;

let ret =

if let Ok(val) = ret {
    return bincode::deserialize(&val).unwrap();

return default_value


error[E0597]: `val` does not live long enough
--> src/models/
25 |         return deserialize(&val).unwrap()
   |                             ^^^ borrowed value does not live long enough
26 |     }
   |     - borrowed value only lives until here


Your two code snippets appear to have a different deserialize fn called, unless the 2nd has brought bincode into scope. What’s the exact code?


deserialize is bincode::deserialize


The error happend at bincode::deserialize(&val), which ret: Result<Vec and, bincode::deserialize expect a &[u8]

if let Ok(val) = ret {
    return bincode::deserialize(&val).unwrap();


Ok - just wanted to make sure it’s the same thing.

I think the issue is in your fn signature - it’s having the caller specifying the 'de lifetime and saying the result might borrow from the serializer which itself has the same 'de lifetime. Yet the function deserializes from a Vec that dies in the function. I’m guessing you meant to either say T: DeserializeOwned or the longer version T: for<'de> Deserialize<'de> (and remove the other 'de from the fn signature).


Check out this explanation of deserializer lifetimes which includes a discussion of how Deserialize<'de> is different from for<'de> Deserialize<'de> in trait bounds.