Last active
October 5, 2022 18:59
-
-
Save benbr8/c71aabe4ce284800a6a9d2cbe8e6e64c to your computer and use it in GitHub Desktop.
Pass async functions with `BoxFuture`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// [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