如何接受异步函数作为参数? [英] How to accept an async function as an argument?

查看:94
本文介绍了如何接受异步函数作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制将闭包/函数作为参数的行为和人体工程学,就像map一样:iterator.map(|x| ...).

I would like to replicate the behavior and ergonomics of taking a closure/function as an argument much like map does: iterator.map(|x| ...).

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

I've noticed that some library code allows passing in async functionality, but this method doesn't allow me to pass in arguments:

pub fn spawn<F, T>(future: F) -> JoinHandle<T>
where
    F: Future<Output = T> + Send + 'static,
    T: Send + 'static,

spawn(async { foo().await });

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

I'm hoping to do one of the following:

iterator.map(async |x| {...});

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

推荐答案

async函数实际上是作为返回impl Future返回的.一旦知道,就可以结合现有的Rust技术来接受函数/闭包,从而产生具有两种泛型类型的函数:

async functions are effectively desugared as returning impl Future. Once you know that, it's a matter of combining existing Rust techniques to accept a function / closure, resulting in a function with two generic types:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆