Skip to content

Instantly share code, notes, and snippets.

@tungli
Created February 12, 2021 17:00
Show Gist options
  • Save tungli/f89599edd09ab192707c9df2b56a06c8 to your computer and use it in GitHub Desktop.
Save tungli/f89599edd09ab192707c9df2b56a06c8 to your computer and use it in GitHub Desktop.
use futures::{
pin_mut,
future::Either,
future::self,
executor::block_on,
};
async fn race_tasks() -> usize {
// These two futures have different types even though their outputs have the same type
let future1 = async {
let () = future::pending().await; // will never finish
1
};
let future2 = async {
future::ready(2 as usize).await
};
// 'select' requires Future + Unpin bounds
pin_mut!(future1);
pin_mut!(future2);
match future::select(future1, future2).await {
Either::Left((value1, _)) => value1, // `value1` is resolved from `future1`
// `_` represents `future2`
Either::Right((value2, _)) => value2, // `value2` is resolved from `future2`
// `_` represents `future1`
}
}
fn main() {
let finished_first = block_on(race_tasks());
assert!(finished_first == 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment