Specify lifetime parameter for serde deserialiser

struct S1<T> 
{
    pub data: T
}
    
impl<'a, T> S1<T> where T: Deserialize<'a> {
    fn update() {
        let str_json = String::new(); // let's assume read from file
        self.data = serve_json::from_str(&str_json).unwrap();
    } 
}

this function will produce lifetime related issue due to incorrect specifier. What is the best way to overcome the problem?

You can't. If the deserialized value is borrowed (and that's what the lifetime specifier in Deserialize means), then the value it's borrowing from - the str_json, in this case - must be alive at least as long as the deserialized value itself. You want to either using DeserializeOwned instead of Deserialize<'a>, or pass the String to update function, with the second way being considerably harder.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.