如何接受异步函数作为参数? [英] How to accept an async function as an argument?
问题描述
我想复制将闭包/函数作为参数的行为和人体工程学,就像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;
}
- 如何将Rust函数作为参数传递?
- 从异步fn"返回的期货的具体类型是什么?
- 在Rust中异步/等待的目的是什么?
- 如何在结构中存储异步函数并从结构实例中调用它?
- `|| _ |和有什么区别?异步移动{}`和`异步移动| _ | {}`
- How do you pass a Rust function as a parameter?
- What is the concrete type of a future returned from `async fn`?
- What is the purpose of async/await in Rust?
- How can I store an async function in a struct and call it from a struct instance?
- What is the difference between `|_| async move {}` and `async move |_| {}`
这篇关于如何接受异步函数作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!