Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I pass async closure as an argument of a function in Rust?

I would like to implement an async function that takes async closure as the argument, so it must be called this way somewhere in the code:

my_func(async || { ... }).await;

What is the correct way to specify the data type of the argument?

I have tried this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

async fn my_func<F>(closure: F) where F: Fn() -> dyn std::future::Future<Output = ()> {
   closure.await;
   closure.await;
   closure.await;
}

But I got the error:

expected trait object `dyn Future`, found `async` closure body

>Solution :

The trait bound for async closures is async Fn[Once/Mut](Args) -> ReturnType (although this may be changed):

#![feature(async_closure)]

async fn my_func<F>(closure: F)
where
    F: async Fn(),
{
    closure().await;
    closure().await;
    closure().await;
}

This translates into a bound on AsyncFn[Once/Mut], but you can’t spell these traits directly.

Old-style bounds should also work, but they won’t have the advantage of async closures, namely, the ability to use borrowed parameters and captures:

#![feature(async_closure)]

async fn my_func<F, Fut>(closure: F)
where
    F: Fn(&str) -> Fut,
    Fut: Future<Output = ()>,
{
    closure("").await;
    closure("").await;
    closure("").await;
}

// Won't compile:
my_func(async |s| { dbg!(s); }).await;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading