Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I fix "borrowed value does not live long enough" from serde_json::from_slice without incurring a memory leak?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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")
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading