异步闭包返回类型的生命周期

时间:2021-06-15 17:44:49

标签: rust async-await rust-lifetimes

考虑以下代码:

async fn f(x: &i32) -> i32 {
    todo!()
}

fn g<F, Fut>(f: F)
where
    F: Send + Sync + 'static,
    for<'a> F: Fn(&'a i32) -> Fut,
    Fut: Future<Output = i32> + Send + Sync,
{
    todo!()
}

fn main() {
    g(f);
}

playground

编译器抱怨

error[E0308]: mismatched types
  --> src/main.rs:17:5
   |
17 |     g(f);
   |     ^ lifetime mismatch
   |
   = note: expected associated type `<for<'_> fn(&i32) -> impl Future {f} as FnOnce<(&i32,)>>::Output`
              found associated type `<for<'_> fn(&i32) -> impl Future {f} as FnOnce<(&'a i32,)>>::Output`
   = note: the required lifetime does not necessarily outlive the empty lifetime
note: the lifetime requirement is introduced here
  --> src/main.rs:10:31
   |
10 |     for<'a> F: Fn(&'a i32) -> Fut,
   |                               ^^^

我认为问题在于异步函数中返回值的生命周期与 x 的生命周期相关,但我不确定如何在 where 子句中表达这一点g

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找这个:

use core::future::Future;

async fn f(x: &i32) -> i32 {
    todo!()
}

fn g<'a, F, Fut>(f: F)
where
    F: Send + Sync + 'static,
    F: Fn(&'a i32) -> Fut,
    Fut: Future<Output = i32> + Send + Sync,
{
    todo!()
}

fn main() {
    g(f);
}

将 x 的生命周期绑定到 g 的生命周期(不确定这是否是您想要的......我不知道在 where 子句中如何做到这一点)