Rust

Async/Await with tokio

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`async fn` returns a future; `.await` drives it. tokio is the de-facto runtime. The `#[tokio::main]` attribute turns `main` into the runtime entry point.
Rust
Raw
// Cargo.toml:
// tokio = { version = "1", features = ["full"] }

use tokio::time::{sleep, Duration};

async fn delayed_greeting(name: &str, delay_ms: u64) -> String {
    sleep(Duration::from_millis(delay_ms)).await;
    format!("Hello, {name}!")
}

#[tokio::main]
async fn main() {
    // Sequential — total time ≈ 100 + 50 = 150ms
    let a = delayed_greeting("Alice", 100).await;
    let b = delayed_greeting("Bob",    50).await;
    println!("{a}  {b}");

    // Concurrent — total time ≈ max(100, 50) = 100ms
    let (a, b) = tokio::join!(
        delayed_greeting("Alice", 100),
        delayed_greeting("Bob",    50),
    );
    println!("{a}  {b}");
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.