Passing async function or closure as parameter

If someone ever lands on this in the future, here a sample async function passed as parameter which can be run in the Rust playground:

use std::future::Future;

type MyParam = u64;
type MyResult = u64;

async fn count(
    value: MyParam,
) -> MyResult {
    value + 1
}

async fn execute<F, Fut>(
    f: F,
    value: MyParam,
) -> MyResult
where
    F: FnOnce(MyParam) -> Fut,
    Fut: Future<Output = MyResult>,
{
    f(value).await
}

#[tokio::main]
async fn main() {
    let value = execute(count, 1).await;
    println!("{:?}", value);
}
3 Likes