< 返回版块

yuyidegit 发表于 2023-05-24 10:56

我要怎么标记这个Fut的生命周期为'a呢?

async fn test_async<F, Fut>(f: F)
where
    F: for<'a> Fn(&'a i32) -> Fut + 'static + Send,
    Fut: std::future::Future<Output = ()> + Send,
{
    let a = 1;
    loop {
        f(&a).await;
        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
    }
}

评论区

写评论
Simon 2023-05-26 09:59

把 'static 改成 'a ?

苦瓜小仔 2023-05-24 14:04

当你要描述带生命周期的参数和返回的 Future 之间存在生命周期关联时,Pin<Box<dyn 'lifetime +Future>> 是最简单、最广泛的做法(唯一的不足在于多一次堆分配)。

比如

--
👇
廴壬吉: 看不懂,这个有什么用

作者 yuyidegit 2023-05-24 13:12

感谢苦瓜大佬.

--
👇
苦瓜小仔: Pin<Box>

async fn test_async<F>(f: F)
where
    F: Send + for<'a> Fn(&'a i32) -> futures::future::BoxFuture<'a, ()>
廴壬吉 2023-05-24 11:41

看不懂,这个有什么用

苦瓜小仔 2023-05-24 11:30

Pin<Box>

async fn test_async<F>(f: F)
where
    F: Send + for<'a> Fn(&'a i32) -> futures::future::BoxFuture<'a, ()>
1 共 5 条评论, 1 页