-1
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?

Martin Ayvazyan
  • 429
  • 1
  • 5
  • 16

1 Answers1

0

Deserialize does not necessarily create a copy of the data in str_json. There might be large text sections in str_json that get referenced in the final T instead of being copied into it. That means, the lifetime of the final self.data is identical to the one from str_json, as it might potentially borrow data from str_json. That is also the reason why you have to specify the lifetime 'a in the first place.

Now in your case, the problem is that self.data gets stored in self, while str_json gets dropped at the end of update(). But self.data might still reference data from str_json, so the compiler rightfully complains.

I think what you actually wanted to achieve is that the data from str_json gets copied into self.data instead of just being referenced. For that behaviour, you have the wrong trait, and what you actually want is DeserializeOwned:

use serde::de::DeserializeOwned;

struct S1<T> {
    pub data: T,
}

impl<T> S1<T>
where
    T: DeserializeOwned,
{
    fn update(&mut self) {
        let str_json = String::new(); // let's assume read from file
        self.data = serde_json::from_str(&str_json).unwrap();
    }
}
Finomnis
  • 18,094
  • 1
  • 20
  • 27