0

I am struggling to learn Rust with his lifetime. So I am making the method bellow in a web client wrapper.

pub async fn get_as_bytes<T: serde::Deserialize>(
    &self,
    url: &str,
    headers: Option<HeaderMap>,
) -> Result<T, Box<dyn Error>> {
    let mut req = self.reqwest_client.request(reqwest::Method::GET, url);

    if let Some(hds) = headers {
        req = req.headers(hds);
    }

    let resp: Response = req.send().await?;
    let full = resp.bytes().await?;

    let result = serde_json::from_slice(&full).unwrap();
    Ok(result)
}

When I try to compile I get that:

error[E0106]: missing lifetime specifier
  --> src/webclient.rs:53:41
   |
53 |     pub async fn get_as_bytes<T: serde::Deserialize>(&self, url: &str, headers: Option<HeaderMap>) -> Result<T, Box<dyn Error>> {
   |                                         ^^^^^^^^^^^ expected named lifetime parameter
   |
help: consider introducing a named lifetime parameter
   |
53 |     pub async fn get_as_bytes<'a, T: serde::Deserialize<'a>>(&self, url: &str, headers: Option<HeaderMap>) -> Result<T, Box<dyn Error>> {
   |                               ^^^           ^^^^^^^^^^^^^^^

error[E0597]: `full` does not live long enough
  --> src/webclient.rs:63:45
   |
63 |         let result = serde_json::from_slice(&full).unwrap();
   |                      -----------------------^^^^^-
   |                      |                      |
   |                      |                      borrowed value does not live long enough
   |                      argument requires that `full` is borrowed for `'static`
64 |         Ok(result)
65 |     }
   |     - `full` dropped here while still borrowed

How do I make &full last since I am trying to return it?

4

1 回答 1

1

只是发布作为将来的参考,而不是删除问题。正如@Shepmaster 在问题评论中提到的那样,创建返回实现 serde::Deserialize 的值的函数时的 que Lifetime error解决了这个问题。作为文档,代码将是:

pub async fn get_as_bytes<T: serde::de::DeserializeOwned >(&self, url: &str, headers: Option<HeaderMap>) -> Result<T, Box<dyn Error>> {
        let mut req = self.reqwest_client.request(reqwest::Method::GET, url);

        if let Some(hds) = headers {
            req = req.headers(hds);
        }

        let resp: Response = req.send().await?;
        let full = resp.bytes().await?;

        let result = serde_json::from_slice(&full).unwrap();
        Ok(result)
    }
    ```
于 2020-11-25T19:22:47.400 回答