Type sig of `async fn (x: usize) -> u32`?

What is the type sig of async fn (x: usize) -> u32 ? I need to stuff a bunch of them in a Vec.

Here’s one possible approach:

use futures::prelude::*;
use future::BoxFuture;

async fn foo(n: usize) -> u32 {
    n as u32 + 1
}
async fn bar(n: usize) -> u32 {
    n as u32 * 2
}

#[tokio::main]
async fn main() {
    let mut v: Vec<fn(usize) -> BoxFuture<'static, u32>> = vec![];

    v.push(|n| foo(n).boxed());
    v.push(|n| bar(n).boxed());

    dbg!((v[0])(10).await);
    dbg!((v[1])(10).await);
}

Rust Playground

Or alternatively, you can also do something like

use future::BoxFuture;
use futures::prelude::*;

async fn foo(n: usize) -> u32 {
    n as u32 + 1
}
async fn bar(n: usize) -> u32 {
    n as u32 * 2
}

fn boxed<Fut: Future<Output = u32> + Send + Sync + 'static>(
    x: impl Fn(usize) -> Fut + Send + Sync + 'static,
) -> Box<dyn Fn(usize) -> BoxFuture<'static, u32> + Send + Sync> {
    Box::new(move |n| x(n).boxed())
}

#[tokio::main]
async fn main() {
    let mut v: Vec<Box<dyn Fn(usize) -> BoxFuture<'static, u32> + Send + Sync>> = vec![];

    v.push(boxed(foo));
    v.push(boxed(bar));

    dbg!((v[0])(10).await);
    dbg!((v[1])(10).await);
}

Rust Playground

3 Likes