How to Implement Structured Concurrency in Rust

Implement structured concurrency in Rust by using the tokio crate's JoinSet to manage and clean up child tasks automatically.

Rust does not have built-in structured concurrency; you must use the tokio crate to manage task lifecycles safely. Add the dependency and wrap your asynchronous tasks in a JoinSet to ensure they complete or cancel together.

[dependencies]
tokio = { version = "1", features = ["full"] }
use tokio::task::JoinSet;

#[tokio::main]
async fn main() {
    let mut set = JoinSet::new();
    
    set.spawn(async { println!("Task 1"); });
    set.spawn(async { println!("Task 2"); });
    
    while let Some(res) = set.join_next().await {
        res.unwrap();
    }
}