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

标签 asynchronous rust async-await closures future

我想复制将闭包/函数作为参数的行为和人体工程学,很像 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/

    相关文章:

    asynchronous - Dart 中的 await 关键字会自动处理数据依赖吗?

    javascript - Node.js - Mocha did() 方法在之前的测试中导致错误

    rust - 无法将互斥量中的向量附加到另一个向量

    rust - 在编译期间如何在宏中列出给定类型的所有已实现特征?

    javascript - 如何在异步调度完成后执行组件中的方法(thunk 或 Action 创建者)?

    javascript - 为什么我的异步函数不与回调结合产生结果?

    c++ - 在 QtConcurrent::run 中使用 QSqlDatabase 连接(伪连接池)

    rust - 为什么我的素数筛法包括数字 49?

    async-await - 为什么 `Box<dyn Sink>` 在使用 Tokio 和实验性异步/等待支持时不实现 `Sink` 特征?

    c# - 异步方法调用异步方法并等待另一个方法(http 客户端)