How to resolve life time issue in a function?

Hi team,

I'm trying to introduce template for a fuction, and this function call another fn with reference object. So I got an lifetime error as follow, any suggestions?

     pub async fn get<'a, 'b, T: serde::Deserialize<'b>>(
         &'a self,
         path: &'a String,
     ) -> Result<T, RestError> {
         let data = self.execute_request(Method::GET, path, None).await?;
         let data = serde_json::from_str(&data)
             .map_err(|_| RestError::InvalidConfig("invalid response".to_string()))?;
 
         Ok(data)
     }

Here's the output of cargo build:

    |
105 |     pub async fn get<'a, 'b, T: serde::Deserialize<'b>>(
    |                          -- lifetime `'b` defined here
...
110 |         let data = serde_json::from_str(&data)
    |                    ---------------------^^^^^-
    |                    |                    |
    |                    |                    borrowed value does not live long enough
    |                    argument requires that `data` is borrowed for `'b`
...
114 |     }
    |     - `data` dropped here while still borrowed

The Deserialize trait is not meant to be able to handle such a function design where you borrow from a local variable (data). Luckily serde also provides the DeserializeOwned trait you can use to get the 'b lifetime out of the way. This is the relevant section about lifetimes during deserialization from the documentation.

2 Likes

Thanks, DeserializeOwned works to me.

1 Like

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.