Consider the following piece of code:
pub async fn parse_bytes<'a, R: Deserialize<'a>>(_query: serde_json::Value) -> R {
let result: Vec<u8> = vec![]; // fetch_result(&query).await
serde_json::from_slice::<R>(result.as_slice())
.expect("Can't parse bytes response")
}
Error
It doesn’t compile:
`result` does not live long enough
borrowed value does not live long enough
Tentative solution
Providing result.leak() instead works, but I’m not sure it’s the right solution: the method’s documentation recites:
This function is mainly useful for data that lives for the remainder of the program’s life. Dropping the returned reference will cause a memory leak
And the returned reference is dropped as soon as the function ends.
Question
How do I fix the above without incurring a memory leak?
>Solution :
Use DeserializeOwned instead.
use serde::de::DeserializeOwned;
pub async fn parse_bytes<R: DeserializeOwned>(_query: serde_json::Value) -> R {
let result: Vec<u8> = vec![]; // fetch_result(&query).await
serde_json::from_slice::<R>(result.as_slice())
.expect("Can't parse bytes response")
}