如何指示异步函数返回值的生存期与参数相同?



我们可以将正常函数与非静态参数匹配,如下所示:

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

由于异步函数返回匿名未来,我们不能指示匿名未来的生存期与参数相同:

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

编译器会抱怨:

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

我该如何匹配它?

您需要声明:

  1. 闭包接受一个与参数具有相同生存期的引用
  2. 返回的future返回一个与参数具有相同生存期的引用
  3. 返回的future捕获一个与参数具有相同生存期的引用
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
}

最新更新