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


#1
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 = config.select(data)
                .filter(name.eq(key))
                .first::<Vec<u8>>(conn);

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

return default_value

}


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

#3

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?


#4

deserialize is bincode::deserialize


#5

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();
}

#6

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).


#7

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.