Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

Async & concurrency

TypeScript promises, Go goroutines/context, Rust futures with Tokio where named, and C++ threads/futures. Runtime and cancellation rules differ; optional setup is identified in each entry.

Create async work

Rust

Calling an async function creates a future. It makes progress when polled, typically by awaiting it or spawning it on an executor.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
async fn work() -> usize { 42 }
let future = work();
let value = future.await;

Wait for a value

Rust

.await polls the future to completion while allowing the executor to run other ready tasks.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let value = future.await;

Retain ownership of a background task

Rust

tokio::spawn schedules work and returns a JoinHandle. The task must satisfy the required Send and lifetime bounds.

Fragment

Dropping a Tokio JoinHandle detaches the task; it does not cancel it.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let handle = tokio::spawn(async move { work().await });
let value = handle.await?;

Sequential awaits versus overlapping work

Rust

Tokio join! polls multiple futures concurrently in one task. It does not create separate threads.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let (a, b) = tokio::join!(load_left(), load_right());

Let other work progress

Rust

yield_now asks Tokio to yield the current task. Futures that never yield can still monopolize executor capacity.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
tokio::task::yield_now().await;

Wait for all successful results

Rust

try_join! returns when all succeed or on the first observed error; sibling futures held by the macro are dropped.

Fragment

Dropping a spawned task’s JoinHandle does not stop that spawned task.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let (a, b) = tokio::try_join!(load_left(), load_right())?;

Collect successes and failures

Rust

join! waits for each future, leaving each Result available for independent inspection.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let (left, right) = tokio::join!(load_left(), load_right());
record(left);
record(right);

Propagate async/task failures

Rust

? returns early from a Result-returning function. A spawned task may have both JoinError and an operation Result.

Fragment

The first ? handles joining; the second handles the operation’s Result.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let value = handle.await??;

Clean up after asynchronous work

Rust

RAII/Drop releases owned guards/resources when their scope ends. Drop cannot directly await async cleanup.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let guard = resource.lock().await;
use_resource(&guard);
drop(guard);

Request cancellation

Rust

Dropping an unspawned future stops polling it. For spawned tasks, use an explicit protocol or Tokio JoinHandle::abort.

Fragment

Abort is not a rollback. Already-running spawn_blocking work cannot normally be aborted.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
handle.abort();
let outcome = handle.await;

Bound the duration of work

Rust

Tokio timeout stops waiting and drops the wrapped future on expiry. A non-yielding future can exceed the deadline.

Fragment

If the wrapped future is a JoinHandle, dropping it detaches the task instead of stopping it.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let result = tokio::time::timeout(
    Duration::from_secs(3),
    work(),
).await;

Wait for the first completion

Rust

tokio::select! polls branches concurrently and drops losing branch futures. Cancellation safety depends on the operations.

Fragment

An in-flight operation may have partial external effects; a dropped JoinHandle detaches.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
tokio::select! {
    value = work() => use_value(value),
    _ = cancel_signal() => {}
}

Delay work with the runtime’s timer model

Rust

Tokio sleep suspends the task. std::thread::sleep blocks the thread.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
tokio::time::sleep(Duration::from_millis(100)).await;

Send a value through a channel

Rust

Tokio bounded mpsc awaits available capacity on send. It has many senders and one receiver.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let (tx, mut rx) = tokio::sync::mpsc::channel(4);
tx.send(job).await?;
let received = rx.recv().await;

Distinguish channel closure from a value

Rust

mpsc recv returns None when the channel is closed and drained. Dropping all senders eventually ends reception.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
while let Some(value) = rx.recv().await {
    use_value(value);
}

Recognize a backpressure boundary

Rust

A bounded mpsc channel awaits capacity; an unbounded channel does not impose that memory bound.

Fragment

Buffer size bounds queued items, not necessarily all upstream or in-flight work.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
tx.send(job).await?;

Consume a stream incrementally

Rust

A Tokio mpsc receiver is consumed with recv. General Stream combinators come from a separate stream crate.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
while let Some(chunk) = chunks.recv().await {
    process(chunk);
}

Limit concurrent operations

Rust

A Tokio semaphore bounds concurrent permit holders. Acquire before spawning to also bound queued spawned tasks.

Fragment

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let slots = Arc::new(tokio::sync::Semaphore::new(4));
let mut tasks = tokio::task::JoinSet::new();
for item in items {
    if tasks.len() >= 4 {
        if let Some(result) = tasks.join_next().await {
            record(result);
        }
    }
    let permit = slots.clone().acquire_owned().await?;
    tasks.spawn(async move {
        let _permit = permit;
        process(item).await
    });
}
while let Some(result) = tasks.join_next().await {
    record(result);
}

Protect a shared invariant

Rust

A Tokio mutex can be held across await when required; prefer a short synchronous critical section with std::sync::Mutex when it fits.

Fragment

Avoid holding unrelated locks during slow I/O.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let mut guard = shared.lock().await;
*guard += 1;
drop(guard);

Move blocking or CPU-heavy work appropriately

Rust

spawn_blocking moves a blocking closure to Tokio’s blocking pool. Bound CPU work separately when necessary.

Fragment

Already running blocking closures cannot normally be canceled through abort.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let value = tokio::task::spawn_blocking(move || {
    compute(input)
}).await?;

Separate shared ownership from synchronization

Rust

Arc shares ownership; it does not make arbitrary interior mutation safe. Mutex/atomics provide the mutation protocol.

Fragment

Send and Sync constrain cross-thread transfer/sharing; they are not deadlock-freedom proofs.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let shared = Arc::new(tokio::sync::Mutex::new(0));

Keep child work inside an owned lifetime

Rust

A JoinSet owns spawned tasks and aborts them when dropped. Cancellation and observing task completion are distinct.

Fragment

Use shutdown().await when its ignore-errors policy fits; otherwise inspect outcomes explicitly.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
tasks.abort_all();
while let Some(result) = tasks.join_next().await {
    record(result);
}

Establish the runtime and API baseline

Rust

Tokio features are opt-in. These examples need an active runtime and relevant macros/time/sync features. The shown dependency settings belong in Cargo.toml.

Fragment

Add imports such as std::time::Duration and std::sync::Arc in examples that use them. Enable net/fs features when using those APIs.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// Cargo.toml: tokio = { version = "1", features = [
//   "rt-multi-thread", "macros", "time", "sync", "io-util"
// ] }
#[tokio::main]
async fn main() {
    tokio::task::yield_now().await;
}

Cancel cooperating siblings and observe completion

Rust

JoinSet owns spawned tasks. On a failure, abort remaining tasks and drain their completions before returning the owner’s error.

Fragment

This assumes task outputs are Result values and the app defines consume/report_failure. Handle join failure and operation failure as distinct outcomes.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
while let Some(outcome) = tasks.join_next().await {
    match outcome {
        Ok(Ok(value)) => consume(value),
        other => {
            tasks.abort_all();
            while tasks.join_next().await.is_some() {}
            return report_failure(other);
        }
    }
}

Bound task records and consume results while launching

Rust

A rolling JoinSet bounds both outstanding tasks and undrained task outputs. Join while launching once the window fills.

Fragment

This bounds retained task slots, not the memory already held by items or the outputs retained by consume. Supply an operation-error policy as well as a join-error policy.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
let mut tasks = tokio::task::JoinSet::new();
for item in items {
    if tasks.len() >= 4 {
        if let Some(result) = tasks.join_next().await {
            consume(result?);
        }
    }
    tasks.spawn(async move { work(item).await });
}
while let Some(result) = tasks.join_next().await {
    consume(result?);
}

Account for progress when a wait is canceled

Rust

Tokio mpsc Receiver::recv is cancellation safe: if another select branch wins, that receive has not consumed a message. read_exact can partially fill a buffer before cancellation.

Fragment

Cancellation safety is specific to the API and operation, not a property of all async I/O.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
tokio::select! {
    message = rx.recv() => handle(message),
    _ = shutdown() => {}
}
// Do not restart read_exact blindly after dropping
// a partially progressing read without tracking protocol state.