HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

How to accept an async function as an argument?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
accepthowfunctionargumentasync

Problem

I would like to replicate the behavior and ergonomics of taking a closure/function as an argument much like map does: iterator.map(|x| ...).

I've noticed that some library code allows passing in async functionality, but this method doesn't allow me to pass in arguments:

pub fn spawn(future: F) -> JoinHandle
where
    F: Future + Send + 'static,
    T: Send + 'static,


spawn(async { foo().await });


I'm hoping to do one of the following:

iterator.map(async |x| {...});


async fn a(x: _) {}
iterator.map(a)

Solution

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: F)
where
    F: FnOnce(i32, i32) -> Fut,
    Fut: Future,
{
    f(1, 2).await;
}


This can also be written as

use std::future::Future;

async fn example(f: impl FnOnce(i32, i32) -> Fut)
where
    Fut: Future,
{
    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 |_| {}

Code Snippets

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

Context

Stack Overflow Q#60717746, score: 78

Revisions (0)

No revisions yet.