Skip to content

Instantly share code, notes, and snippets.

@benbr8
Last active October 5, 2022 18:59
Show Gist options
  • Save benbr8/c71aabe4ce284800a6a9d2cbe8e6e64c to your computer and use it in GitHub Desktop.
Save benbr8/c71aabe4ce284800a6a9d2cbe8e6e64c to your computer and use it in GitHub Desktop.
Pass async functions with `BoxFuture`
// [dependencies]
// futures = "*"
// async-std = "*"
use futures::{future::BoxFuture, FutureExt};
use async_std::task;
fn main() {
let mut functions: Vec<fn(usize) -> BoxFuture<'static, usize>> = Vec::new();
functions.push( |x| { add_one(x).boxed() } );
functions.push( |x| { add_two(x).boxed() } );
functions.push( |x| { add_three(x).boxed() } );
let mut j = 0;
task::block_on(async {
for f in functions.drain(..) {
j = f(j).await;
dbg!(j);
}
});
}
async fn add_one(x: usize) -> usize {
x+1
}
async fn add_two(x: usize) -> usize {
x+2
}
async fn add_three(x: usize) -> usize {
x+3
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment