How to accept an async function as an argument?
The async |...| expr
closure syntax is available on the nightly channel enabling the feature async_closure
.
#![feature(async_closure)]
use futures::future;
use futures::Future;
use tokio;
pub struct Bar;
impl Bar {
pub fn map<F, T>(&self, f: F)
where
F: Fn(i32) -> T,
T: Future<Output = Result<i32, i32>> + Send + 'static,
{
tokio::spawn(f(1));
}
}
async fn foo(x: i32) -> Result<i32, i32> {
println!("running foo");
future::ok::<i32, i32>(x).await
}
#[tokio::main]
async fn main() {
let bar = Bar;
let x = 1;
bar.map(foo);
bar.map(async move |x| {
println!("hello from async closure.");
future::ok::<i32, i32>(x).await
});
}
See the 2394-async_await RFC for more detalis
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 |_| {}`