0

我有这个功能正在对手动创建的期货做一些工作。

    pub type Response = Pin<Box<dyn Future<Output = Result<T, Error>> + Send>>

    pub fn get_list<T: DeserializeOwned + Send + 'static, P: serde::Serialize + Clone + Send>(
        &self,
        path: &str,
        params: P,
    ) -> Response<List<T>> {
        use futures::future::FutureExt;

        let resp: Response<List<T>> = self.get_query(path, params.clone());

        let params = params.clone();
        let resp = resp.then(move |res| async move {
            let params = params; // Take ownership of params.
            match res {
                Ok(list) => list.params(&params),
                Err(e) => Err(e),
            }
        });

        return Box::pin(resp);
    }

我收到错误:

   the parameter type `P` may not live long enough
...so that the type `futures_util::future::Then<Pin<Box<dyn futures_util::Future<Output = Result<List<T>, error::Error>> + std::marker::Send>>, impl futures_util::Future, [closure@src/client/async.rs:142:30: 148:10]>` will meet its required lifetime bounds

我不想做P静态,但我不介意克隆我的解决方案。我的理解是 usingasync move应该移动参数并获得所有权,所以我不需要 P 上的任何生命周期。但显然生命周期仍然存在一些奇怪的事情。

有什么建议么?

4

1 回答 1

1

为此,您需要P: 'static. 现在,您正在克隆params,但这不会阻止该类型P包含在某些时候会变为无效的引用,无论这些引用是否已被克隆。通过添加P: 'static边界,您禁止P包含此类引用。

P: 'static可以理解为“类型的值P可以保留,只要它们的所有者想要”。这并不意味着它params需要无限期地生活,只是它可以。

于 2021-10-22T23:36:49.630 回答