gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:23:43 26 4
gpt4 key购买 nike

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

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com