如何接受异步函数作为参数?

How to accept an async function as an argument?

我想复制将 closure/function 作为参数的行为和人体工程学,就像 map 所做的那样:iterator.map(|x| ...).

我注意到一些库代码允许传入异步功能,但是这个方法不允许我传入参数:

pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,
spawn(async { foo().await });

我希望执行以下操作之一:

iterator.map(async |x| {...});
async fn a(x: _) {}
iterator.map(a)

async |...| expr 闭包语法在启用功能 async_closure 的夜间频道上可用。

#![feature(async_closure)]

use futures::future;
use futures::Future;
use tokio;

pub struct Bar;

impl Bar {
    pub fn map<F, T>(&self, f: F)
    where
        F: Fn(i32) -> T,
        T: Future<Output = Result<i32, i32>> + Send + 'static,
    {
        tokio::spawn(f(1));
    }
}

async fn foo(x: i32) -> Result<i32, i32> {
    println!("running foo");
    future::ok::<i32, i32>(x).await
}

#[tokio::main]
async fn main() {
    let bar = Bar;
    let x = 1;

    bar.map(foo);

    bar.map(async move |x| {
        println!("hello from async closure.");
        future::ok::<i32, i32>(x).await
    });
}

查看2394-async_await RFC了解更多详情

async 函数被有效地脱糖为返回 impl Future。一旦你知道了这一点,那就是结合现有的 Rust 技术来接受一个函数/闭包,从而产生一个具有两种泛型类型的函数:

use std::future::Future;

async fn example<F, Fut>(f: F)
where
    F: FnOnce(i32, i32) -> Fut,
    Fut: Future<Output = bool>,
{
    f(1, 2).await;
}

这也可以写成

use std::future::Future;

async fn example<Fut>(f: impl FnOnce(i32, i32) -> Fut)
where
    Fut: Future<Output = bool>,
{
    f(1, 2).await;
}