本文介绍了如何指示异步函数返回值的生命周期与参数相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以像这样用非静态参数匹配一个普通函数:

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

由于异步函数返回匿名future,我们不能表明匿名future的生命周期与参数相同:

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

编译器会抱怨:

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
}

这篇关于如何指示异步函数返回值的生命周期与参数相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:21