Skip to content

Instantly share code, notes, and snippets.

@singulared
Created May 23, 2019 14:11
Show Gist options
  • Save singulared/35de884fd6b47947b2282fa7efa5d4e6 to your computer and use it in GitHub Desktop.
Save singulared/35de884fd6b47947b2282fa7efa5d4e6 to your computer and use it in GitHub Desktop.
Collecting vector of future's results in rust
use futures; // 0.1.26
use futures::prelude::*;
use futures::future::{ok, err};
use futures::stream::*;
use futures::future::FutureResult;
fn future_result(x: i32) -> FutureResult<i32, i32> {
match x {
1 => ok(42),
2 => ok(24),
_ => err(0),
}
}
fn future(x: i32) -> Box<Future<Item = i32, Error = i32>> {
match x {
1 => Box::new(ok(42)),
2 => Box::new(ok(24)),
_ => Box::new(err(0)),
}
}
fn main() {
let f: Vec<FutureResult<i32, i32>> = vec![
future_result(1),
future_result(2),
future_result(3),
future_result(4),
];
let f: Result<Vec<i32>, i32> = futures_unordered(f)
.then(|result| match result {
Ok(e) => Ok(e),
Err(e) => Ok(e),
})
.collect().wait();
println!("FutureResult: {:?}", f);
let f: Vec<Box<Future<Item = i32, Error = i32>>> = vec![
future(1),
future(2),
future(3),
future(4),
];
let f: Result<Vec<i32>, i32> = futures_unordered(f)
.then(|result| match result {
Ok(e) => Ok(e),
Err(e) => Ok(e),
})
.collect().wait();
println!("Boxed Future: {:?}", f);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment