简体   繁体   中英

Lifetime of async closure return type

Consider the following code:

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

The compiler complains with

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,
   |                               ^^^

I think the issue is that the lifetime of the return value in the async function is tied to the lifetime of x , but I'm not sure how to express this in the where clause for g ?

i think you are looking for this:

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);
}

Bind the lifetime of x to that of g (don't know for sure if this is what you want.. i don't know of a way to do this in the where clause)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM