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.

Libraries: concurrency & network

Doing several things at once and talking to other machines: threads and tasks, locks and atomics, CPU parallelism, event loops, cancellation, request context, sockets, TLS and HTTP.

Concurrency: Promise, sync + goroutines, std::thread/std::sync, <thread>

Rust

std::thread runs operating-system threads (spawn, join, and scope for threads that borrow local data). std::sync provides Arc (shared ownership across threads), Mutex and RwLock, atomics and mpsc channels. The compiler's Send and Sync checks reject data races at compile time. For many concurrent I/O tasks, async Rust on the tokio runtime (tokio::spawn, join!, select!) is the usual choice.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

fn fetch_price(id: u64) -> u64 {
    thread::sleep(Duration::from_millis(10 * id)); // stands in for I/O
    id * 100
}

fn main() {
    let prices = Arc::new(Mutex::new(Vec::new())); // shared ownership + locking

    let handles: Vec<_> = (1..=3)
        .map(|id| {
            let prices = Arc::clone(&prices);
            thread::spawn(move || {
                let price = fetch_price(id);
                prices.lock().unwrap().push((id, price));
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }
    println!("{:?}", prices.lock().unwrap());
}

Most used: thread::spawn, thread::scope, JoinHandle::join, Arc, Mutex, RwLock, mpsc::channel, AtomicUsize, tokio::spawn for async.

Locks, atomics & one-time init: Atomics, sync.Once, OnceLock, std::call_once

Rust

std::sync::Mutex owns the value it protects, so the only way to reach the data is through the guard that lock() returns, and the lock is released when the guard is dropped. RwLock allows many readers or one writer. Arc shares ownership across threads (thread::scope avoids it when threads can borrow). Atomics in std::sync::atomic take an Ordering: Relaxed is enough for a standalone counter, Acquire/Release when the atomic publishes other data. LazyLock (Rust 1.80+) initialises a static on first use and OnceLock is set once at runtime.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex, OnceLock};
use std::thread;

static PRICES: LazyLock<HashMap<&str, u64>> = LazyLock::new(|| {
    println!("loading prices"); // first use, from whichever thread gets there first
    HashMap::from([("widget", 250), ("gadget", 900)])
});
static REGION: OnceLock<String> = OnceLock::new(); // set once, at runtime
static REVENUE: AtomicU64 = AtomicU64::new(0);

fn main() {
    REGION.set("eu".to_string()).expect("set only once");
    let stock = Arc::new(Mutex::new(5u32)); // Arc shares it, Mutex guards it

    let handles: Vec<_> = (0..8)
        .map(|_| {
            let stock = Arc::clone(&stock);
            thread::spawn(move || {
                let price = PRICES["widget"];
                let mut left = stock.lock().unwrap(); // Err only if a holder panicked
                if *left > 0 {
                    *left -= 1;
                    REVENUE.fetch_add(price, Ordering::Relaxed); // a lone counter needs no ordering
                }
            }) // the guard drops here, releasing the lock
        })
        .collect();
    for handle in handles {
        handle.join().unwrap();
    }
    let left = *stock.lock().unwrap();
    println!("{} left: {left} revenue: {}", REGION.get().unwrap(), REVENUE.load(Ordering::Relaxed));
}

Most used: Arc::new, Arc::clone, Mutex::new, lock().unwrap(), RwLock read and write, AtomicU64 fetch_add and load, Ordering::Relaxed, Acquire, Release, LazyLock::new, OnceLock set and get, parking_lot as a faster third-party lock.

A thread that panics while holding a Mutex poisons it, and later lock() calls return Err; unwrap() turns that into a panic, and into_inner on the error recovers the data.

A guard lives until the end of its scope: `let left = stock.lock().unwrap();` keeps the lock for the rest of the block, so drop it early or use a smaller block.

Locks are not reentrant: locking a Mutex the same thread already holds deadlocks or panics.

Inside async code, a std MutexGuard must not be held across .await; use tokio::sync::Mutex only when a lock has to be.

CPU parallelism & worker pools: worker_threads, errgroup, rayon, std::jthread

Rust

rayon is the standard data-parallelism crate: change iter() to par_iter() (or into_par_iter()) and a work-stealing thread pool splits the work across cores, with the same map, filter, sum and collect adapters. rayon::join runs two closures potentially in parallel. Without a crate, std::thread::scope starts threads that may borrow local data and are all joined when the scope ends, and available_parallelism reports how many are useful. In async code, tokio::task::spawn_blocking is for blocking I/O; CPU-heavy work belongs on rayon so it does not occupy the blocking pool.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add rayon

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use rayon::prelude::*;
use std::thread;

fn is_prime(n: u64) -> bool {
    n >= 2 && (2..).take_while(|d| d * d <= n).all(|d| n % d != 0)
}

fn main() {
    // rayon: the same adapters, split across a work-stealing pool.
    let primes = (0..200_000u64).into_par_iter().filter(|&n| is_prime(n)).count();
    println!("primes below 200000 = {primes}");

    let (small, large) = rayon::join(|| (0..1_000u64).sum::<u64>(), || (0..1_000_000u64).sum::<u64>());
    println!("joined: {small} {large}");

    // std only: scoped threads may borrow data, and all join when the scope ends.
    let orders: Vec<u64> = (1..=1_000).collect();
    let threads = thread::available_parallelism().map_or(4, |n| n.get());
    let chunk = orders.len().div_ceil(threads);
    let total: u64 = thread::scope(|s| {
        let handles: Vec<_> = orders
            .chunks(chunk)
            .map(|part| s.spawn(move || part.iter().sum::<u64>())) // borrows orders: no Arc
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).sum()
    });
    println!("total: {total}");
}

Most used: par_iter, into_par_iter, par_chunks, map, filter, sum, collect, rayon::join, ThreadPoolBuilder, std::thread::scope, available_parallelism.

rayon closures must be Send + Sync; shared mutable state still needs a Mutex or an atomic, so prefer reductions (sum, reduce, collect) over pushing into shared vectors.

Parallel iterators pay off for work that is large per item or large in total; for a few microseconds of work the splitting overhead wins.

Event loops & async runtimes: EventEmitter, the Go scheduler, tokio, Asio

Rust

Async functions produce futures that do nothing until a runtime polls them, and the standard library ships no runtime. tokio is the standard choice: #[tokio::main] starts a multi-threaded scheduler, tokio::spawn runs tasks, and it provides async networking, timers, channels (mpsc, oneshot, broadcast, watch), synchronization primitives and select!. smol is a smaller alternative, but most libraries are written against tokio.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add tokio --features full

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time::interval;

#[tokio::main] // starts the runtime: a thread pool that polls futures
async fn main() {
    let (tx, mut orders) = mpsc::channel::<u32>(16); // bounded: senders wait when full

    let producer = tokio::spawn(async move {
        // a task: a lightweight future scheduled by the runtime
        for id in 7..10 {
            tx.send(id).await.expect("receiver alive");
        }
    }); // tx is dropped when the task ends, which closes the channel

    let mut tick = interval(Duration::from_millis(100));
    loop {
        tokio::select! { // wait on several event sources at once
            message = orders.recv() => match message {
                Some(id) => println!("received {id}"),
                None => break, // every sender is gone
            },
            _ = tick.tick() => {} // periodic work would go here
        }
    }
    producer.await.expect("producer finished");
    println!("drained");
}

Most used: #[tokio::main], tokio::spawn, JoinHandle, tokio::select!, mpsc::channel, oneshot, tokio::time::sleep and interval, tokio::sync::Mutex, spawn_blocking for blocking I/O (CPU-heavy work belongs on rayon or a dedicated pool). tokio::spawn requires a Send + 'static future, so an Rc or a std MutexGuard held across .await will not compile; prefer std::sync::Mutex unless a lock must be held across .await.

Cancellation & deadlines: AbortController, context, CancellationToken, std::stop_token

Rust

In async Rust, dropping a future cancels it, so cancellation is mostly about choosing what to drop; dropping a JoinHandle, though, detaches the spawned task, which keeps running until you call abort() or signal it. tokio::time::timeout wraps a future with a deadline, tokio::select! races branches and drops the losers, and tokio_util's CancellationToken signals cancellation to many tasks (child_token builds hierarchies). Code that must not stop halfway has to be cancellation-safe: mpsc recv is safe to restart in a select! loop, but read_exact or write_all can lose partial progress. Synchronous threads check an AtomicBool or a channel in their loop.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add tokio --features full && cargo add tokio-util

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::time::Duration;
use tokio::time::{sleep, timeout};
use tokio_util::sync::CancellationToken;

async fn fetch_report() -> &'static str {
    sleep(Duration::from_secs(1)).await; // stands in for slow I/O
    "report"
}

#[tokio::main]
async fn main() {
    let token = CancellationToken::new();
    let trigger = token.clone();
    tokio::spawn(async move {
        sleep(Duration::from_millis(50)).await;
        trigger.cancel(); // cancel by hand...
    });
    tokio::select! {
        report = fetch_report() => println!("{report}"),
        _ = token.cancelled() => println!("stopped: cancelled"), // the loser is dropped
    }

    match timeout(Duration::from_millis(20), fetch_report()).await { // ...or by deadline
        Ok(report) => println!("{report}"),
        Err(elapsed) => println!("stopped: {elapsed}"),
    }
}

Most used: tokio::time::timeout, tokio::select!, CancellationToken::new, cancel, cancelled().await, child_token, JoinHandle::abort, AtomicBool for threads.

Request-scoped context: AsyncLocalStorage, context.WithValue, task_local!, thread_local

Rust

tokio::task_local! declares a value that is set for the duration of a future: KEY.scope(value, future).await makes it visible to KEY.with and try_with anywhere inside that future, across .await points, and concurrent futures each see their own. A spawned task does not inherit it, so wrap the spawned future in its own scope. In practice most services carry request ids in tracing spans (#[instrument] or info_span!), which subscribers attach to every log line; std::thread_local! is the per-thread equivalent for synchronous code.

Complete program

Complete program.

Before you use this

Not in the standard library: cargo add tokio --features full

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::time::Duration;
use tokio::time::sleep;

tokio::task_local! {
    static REQUEST_ID: String;
}

fn log(message: &str) {
    let id = REQUEST_ID.try_with(|id| id.clone()).unwrap_or_else(|_| "-".into()); // Err outside a scope
    println!("[{id}] {message}");
}

async fn load_orders(user: &str, delay: u64) {
    sleep(Duration::from_millis(delay)).await; // the value survives .await
    log(&format!("orders for {user}"));
}

async fn handle(id: &str, user: &str, delay: u64) {
    let work = async {
        log("start");
        load_orders(user, delay).await;
        log("done");
    };
    REQUEST_ID.scope(id.to_string(), work).await; // visible only inside this future
}

#[tokio::main]
async fn main() {
    tokio::join!(handle("r1", "ada", 20), handle("r2", "lin", 10)); // interleaved, never mixed
    tokio::spawn(async { log("spawned") }).await.unwrap(); // spawned tasks start without it
    log("outside");
}

Most used: tokio::task_local!, KEY.scope(value, fut), KEY.with, KEY.try_with, KEY.get for Copy values, tracing::info_span!, #[tracing::instrument], Instrument::instrument, std::thread_local!.

KEY.with panics outside a scope; try_with returns an AccessError instead.

thread_local! values do not follow async tasks, which tokio moves between worker threads at each .await.

TCP & UDP sockets: node:net, net, std::net, Boost.Asio

Rust

std::net provides blocking TCP and UDP: TcpListener::bind and incoming for servers, TcpStream::connect for clients and UdpSocket for datagrams. Streams implement Read and Write, so BufReader and write_all work on them, and set_read_timeout bounds blocking calls. Servers with many connections use tokio::net, which has the same types in async form; rustls or native-tls add TLS.

Complete program

Complete program. Standard library: ships with Rust, no install.

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;

fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:0")?; // port 0: pick a free port
    let address = listener.local_addr()?;

    thread::spawn(move || {
        // an echo server: one thread per connection
        for stream in listener.incoming().flatten() {
            thread::spawn(move || -> std::io::Result<()> {
                let mut line = String::new();
                BufReader::new(stream.try_clone()?).read_line(&mut line)?;
                (&stream).write_all(line.as_bytes())
            });
        }
    });

    let mut client = TcpStream::connect(address)?;
    client.write_all(b"ping\n")?;
    let mut reply = String::new();
    BufReader::new(client).read_line(&mut reply)?;
    print!("echoed: {reply}");
    Ok(())
}

Most used: TcpListener::bind, incoming, TcpStream::connect, set_read_timeout, UdpSocket::bind, send_to, recv_from, tokio::net::TcpListener.

TLS & certificates: node:tls, crypto/tls + crypto/x509, rustls, OpenSSL

Rust

The standard library has no TLS. rustls is the common pure-Rust implementation (TLS 1.2 and 1.3, no OpenSSL): build a ClientConfig from a RootCertStore, create a ClientConnection for a server name, and wrap a TcpStream in StreamOwned for blocking Read and Write. Roots come from webpki-roots (Mozilla's list compiled in), rustls-native-certs (the OS store as a list) or rustls-platform-verifier (the OS verifier itself, best for apps); tokio-rustls provides TlsConnector for async code, and reqwest and hyper use rustls through features. native-tls wraps the platform library (OpenSSL, Secure Transport, SChannel) when that is required.

Complete program

Complete program; needs network access to example.com.

Before you use this

Not in the standard library: cargo add rustls@0.23 webpki-roots (rustls uses the aws-lc-rs crypto provider by default, which compiles C code; the ring feature is the alternative).

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use std::io::{BufRead, BufReader, Write};
use std::net::TcpStream;
use std::sync::Arc;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Trust Mozilla's root CAs, compiled into the binary by webpki-roots.
    let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let config = rustls::ClientConfig::builder()
        .with_root_certificates(roots)
        .with_no_client_auth();

    let name = "example.com".try_into()?; // checked against the certificate and sent as SNI
    let conn = rustls::ClientConnection::new(Arc::new(config), name)?;
    let mut tls = rustls::StreamOwned::new(conn, TcpStream::connect("example.com:443")?);

    // The handshake runs on first use; a bad certificate fails here with an error.
    tls.write_all(b"HEAD / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n")?;
    let mut status = String::new();
    BufReader::new(&mut tls).read_line(&mut status)?;
    println!("{:?} {}", tls.conn.protocol_version(), status.trim_end());
    Ok(())
}

Most used: RootCertStore, webpki_roots::TLS_SERVER_ROOTS, ClientConfig::builder().with_root_certificates(..).with_no_client_auth(), ClientConnection::new, StreamOwned, tokio_rustls::TlsConnector, CertificateDer::pem_file_iter (the PemObject trait) to load PEM files.

rustls can only skip verification through a custom ServerCertVerifier under config.dangerous(); never ship one. Without verification anyone on the network path can impersonate the server, so add the private CA to the RootCertStore instead.

Output depends on the server: example.com currently negotiates TLS 1.3.

HTTP: fetch + node:http, net/http, reqwest/axum, cpp-httplib

Rust

The standard library has TCP (std::net) but no HTTP. The common stack is async: tokio as the runtime, reqwest as the client, and axum as the server framework; reqwest and axum are built on the hyper HTTP implementation, while actix-web has its own stack. axum handlers are async functions whose arguments, called extractors (Path, Query, Json), are parsed from the request.

Complete program

Complete program that needs network access; it keeps serving until stopped.

Before you use this

Not in the standard library: cargo add tokio --features full && cargo add reqwest axum serde_json

src/main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
use axum::{Json, Router, extract::Path, routing::get};
use serde_json::{Value, json};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Client: reqwest
    let response = reqwest::get("https://example.com/").await?;
    println!("{}", response.status());

    // Server: axum on the tokio runtime
    let app = Router::new().route("/orders/{id}", get(order));
    let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
    axum::serve(listener, app).await?;
    Ok(())
}

async fn order(Path(id): Path<String>) -> Json<Value> {
    Json(json!({ "id": id }))
}

Most used: reqwest::get, reqwest::Client, axum::Router::new().route, extract::Path, Json, tokio::net::TcpListener, axum::serve.