How to accept an async function as an argument?

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

This can also be written as

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 |_| {}`

Leave a Comment