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

Ska*_*ett 12 closures asynchronous future rust async-await

我想就像复制行为,并采取封闭/函数作为参数人体工程学map的作用:iterator.map(|x| ...)

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

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

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

iterator.map(async |x| {...});
Run Code Online (Sandbox Code Playgroud)
async fn a(x: _) {}
iterator.map(a)
Run Code Online (Sandbox Code Playgroud)

She*_*ter 18

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;
}
Run Code Online (Sandbox Code Playgroud)

这也可以写成

use std::future::Future;

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


att*_*ona 5

所述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
    });
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参阅2394-async_await RFC


归档时间:

查看次数:

4673 次

最近记录:

5 年,7 月 前