我想复制将闭包/函数作为参数的行为和人体工程学,很像 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
函数被有效地脱糖为返回 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;
}
关于asynchronous - 如何接受异步函数作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60717746/