Skip to content

Instantly share code, notes, and snippets.

@ming900518
Created December 27, 2023 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ming900518/80304204b2f9eb7c927a2ae863a2390e to your computer and use it in GitHub Desktop.
Save ming900518/80304204b2f9eb7c927a2ae863a2390e to your computer and use it in GitHub Desktop.
Rust Async Closure Test
#![feature(async_closure)]
use futures_util::future::join_all;
use std::{iter::zip, time::Duration};
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let ids = [1, 2, 3, 4];
let durations = [200, 100, 300, 250];
join_all(
zip(ids, durations)
.map(async move |(id, duration)| {
let async_fn = hello(id, Duration::from_millis(duration)).await;
async_fn
})
.collect::<Vec<_>>(),
)
.await;
}
async fn hello(id: usize, duration: Duration) {
sleep(duration).await;
println!("Hello, {id}");
}
@ming900518
Copy link
Author

ming900518 commented Dec 27, 2023

Result

   Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 1.42s
     Running `target/debug/playground`

Hello, 2
Hello, 1
Hello, 4
Hello, 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment