How to indicate that the lifetime of an async function's return value is the same as a parameter?

Viewed 951

We can match a normal function with non-static parameter like this:

fn processor(data: &i32) -> &i32 {
    data
}

fn process<'b>(data: &'b i32, processor: impl 'static + for<'a> Fn(&'a i32) -> &'a i32) -> &'b i32 {
    processor(data)
}

fn main() {
    let data = 1;
    println!("data: {}", process(&data, processor));
}

Since async functions return anonymous futures, we cannot indicate that the lifetime of anonymous future is the same as the parameter:

use std::future::Future;

async fn processor(data: &i32) -> &i32 {
    data
}

async fn process<'b, F>(data: &'b i32, processor: impl 'static + Fn(&i32) -> F) -> &'b i32
where
    F: 'b + Future<Output = &'b i32>,
{
    processor(data).await
}

async fn _main() {
    let data = 1;
    println!("data: {}", process(&data, processor).await);
}

The compiler will complain:

error[E0271]: type mismatch resolving `for<'r> <for<'_> fn(&i32) -> impl std::future::Future {processor} as std::ops::FnOnce<(&'r i32,)>>::Output == _`
  --> src/lib.rs:16:26
   |
7  | async fn process<'b, F>(data: &'b i32, processor: impl 'static + Fn(&i32) -> F) -> &'b i32
   |          -------                                                             - required by this bound in `process`
...
16 |     println!("data: {}", process(&data, processor).await);
   |                          ^^^^^^^ expected bound lifetime parameter, found concrete lifetime

How can I match it?

1 Answers

You need to state that:

  1. the closure accepts a reference with the same lifetime as the parameter.
  2. the returned future returns a reference with the same lifetime as the parameter.
  3. the returned future captures a reference with the same lifetime as the parameter.
async fn process<'b, F, Fut>(data: &'b i32, processor: F) -> &'b i32
where
    F: Fn(&'b i32) -> Fut,
    //     ^^ [1]
    F: 'static,
    Fut: Future<Output = &'b i32> + 'b,
    //                    ^^ [2]    ^^ [3]
{
    processor(data).await
}
Related