The Rust Handbook: from ownership to async CLIs and Axum web backends

By

Tagged: Rust

Learn modern Rust from scratch: Cargo, types, UTF-8 strings, ownership and lifetimes, structs, enums, error handling, traits, iterators, smart pointers, concurrency, serde, macros, async Tokio, a real CLI with clap and reqwest, and a production Axum + SQLite web API.

Rust used to feel like a language reserved for operating systems, browser engines, and game studios.

That changed fast. Today Rust powers the developer tools you probably run every day (ripgrep, uv, ruff, rolldown, zed), cloud infrastructure at AWS and Cloudflare, and now full-stack web frameworks like Laravel Rust.

The big reason is simple. Rust gives you the speed, tiny memory footprint, and single-binary deployment of C without garbage collection pauses and without the memory-corruption bugs that haunt C and C++.

Even better, Rust’s strict compiler pairs remarkably well with AI coding agents. When an agent writes code in a dynamic language, subtle type bugs or race conditions can hide until production. In Rust, the compiler rejects invalid borrows, missing error paths, and data races before a single test runs.

This handbook takes you from installing Rust and understanding the borrow checker all the way through traits, iterators, threads, file I/O, serde, macros, unsafe boundaries, async Tokio, building a real concurrent CLI tool (urlprobe), and shipping a tested Axum + SQLite web API (pulseapi).

Every command, compiler error, test run, binary size, and latency number on this page comes from compiling and running a real Cargo workspace on my Mac using the latest Rust release (Rust 1.100.1).

Find your way around this handbook

This is a full-length reference guide. Jump straight to the part you need:

If you want toJump to
Compare Rust to C, Go, and TypeScript and set up CargoWhy Rust, installation, and Cargo
Master types, overflow rules, conversions, and control flowVariables, types, and control flow
Understand String, &str, UTF-8, Cow, Vec, and mapsStrings, slices, and standard collections
Make ownership, borrowing, and lifetimes finally clickOwnership, borrowing, and lifetimes
Model real domains with structs, enums, and matchStructs, enums, and pattern matching
Handle missing values and failures with Option, Result, and ?Error handling with Option, Result, and ?
Write reusable code with traits, generics, closures, and iteratorsGenerics, traits, closures, and iterators
Use Box, Rc, Cell, RefCell, Deref, and DropSmart pointers, interior mutability, and RAII
Run safe parallel code with scoped threads, channels, and ArcThreads, channels, and shared-state concurrency
Organize workspaces, read/write files, and parse JSON with serdeModules, Cargo workspaces, files, and serde
Write fast tests, macros, and safe unsafe wrappersTesting, Clippy, macros, and unsafe Rust
Understand async/await, Tokio channels, select!, and blocking rulesAsync Rust and Tokio
Build a real concurrent CLI tool with clap and reqwestProject 1: building urlprobe, an async CLI
Build a tested HTTP API with Axum, Tower, and SQLiteProject 2: building pulseapi with Axum and SQLite
Optimize release binaries, cross-compile, and deployRelease builds, cross-compilation, and deployment
Decide when Rust is worth the learning curveHow I would use Rust

Why Rust, installation, and Cargo

Most programming languages force a trade-off between safety and control.

Languages like JavaScript, Python, PHP, and Go protect memory with a garbage collector. That makes writing code fast, at the cost of extra RAM and periodic GC pauses. Languages like C and C++ give you direct control over memory and maximum speed, at the cost of manual malloc/free, dangling pointers, and buffer overflows.

Rust takes a third path. It enforces memory safety at compile time through ownership and borrowing. There is no garbage collector running in the background, and there are no manual free() calls to forget.

Here is how Rust stacks up against the other languages I cover on this site:

LanguageMemory modelBuild outputCompile speedTypical web RSSBest fit
RustCompile-time ownershipSingle native binarySlower (seconds)5 to 30 MBCLIs, high-load APIs, systems tools
GoLow-pause GCSingle native binaryVery fast (< 1s)15 to 40 MBNetwork services, DevOps tools
CManual malloc/freeNative binaryFast< 5 MBKernels, embedded, C libraries
TypeScript (Node/Bun)Tracing GC (V8/JSC)JS + runtimeInstant40 to 150 MBFull-stack web UIs, quick scripts

Installing Rust with rustup

The official way to install Rust on macOS and Linux is rustup, the toolchain manager:

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

On Windows, download and run rustup-init.exe from rust-lang.org.

rustup installs 3 core tools into ~/.cargo/bin:

  • rustc: the Rust compiler.
  • cargo: the package manager, build tool, and test runner.
  • rustup: the tool that updates toolchains (rustup update), switches channels (stable, beta, nightly), and adds cross-compilation targets (rustup target add).

Verify your setup in a new terminal:

rustc --version
cargo --version

On my Mac, I am running:

rustc 1.100.1 (20ddd0171 2026-11-25)
cargo 1.100.1 (3acc79c0c 2026-11-05)

Rust releases and editions

Rust ships a new minor release every 6 weeks with strict backward compatibility. Code written for Rust 1.0 in 2015 still compiles on Rust 1.100 today.

Every three years, Rust also publishes an Edition (2015, 2018, 2021, 2024). Editions let the language clean up sharp edges and introduce new keywords without breaking old crates. A crate on Edition 2024 can depend freely on a crate on Edition 2021, and edition = "2024" is the current default Cargo writes into new projects.

Creating your first project with Cargo

You rarely invoke rustc directly. You work through Cargo for everything.

Create a new binary project and run it:

cargo new hello_rust
cd hello_rust
cargo run

Cargo generates Cargo.toml (your manifest, similar to package.json or composer.json), Cargo.lock (exact pinned versions), and src/main.rs:

fn main() {
    println!("Hello, world!");
}

Notice the ! in println!. Anything ending in ! is a macro, which expands at compile time. That is how println! checks format placeholders before your program ever runs.

Cargo commands you will use every day

Here is the core daily toolkit that ships with every Rust installation:

CommandWhat it doesWhen to run it
cargo checkType-checks and borrow-checks without linking a binaryConstantly while editing (fastest loop)
cargo runCompiles in debug mode and runs the binaryTesting your program locally
cargo testRuns unit tests, integration tests, and doc testsAfter every change
cargo clippyRuns Rust’s official linter for idiomatic codeBefore committing (-- -D warnings in CI)
cargo fmtFormats every file to standard Rust styleOn save in your editor
cargo doc --openBuilds local HTML docs for your crate and every dependencyOffline API browsing
cargo build --releaseCompiles with full LLVM optimizationsBefore benchmarking or deploying

Managing dependencies and feature flags

To add a crate from crates.io, run cargo add:

cargo add serde --features derive
cargo add tokio --features macros,rt-multi-thread
cargo add tower --dev --features util

Rust crates rely heavily on Cargo feature flags so you only compile what you use. Turning off default-features and picking only ["rustls", "http2"] on reqwest, for instance, keeps OpenSSL out of your build and makes cross-compilation much simpler.

Newer Cargo versions also warn you automatically about unused entries in [dependencies] (cargo::unused_dependencies), nudging you to move test-only crates into [dev-dependencies].

Editor setup with rust-analyzer

Install rust-analyzer in your editor before writing serious Rust. Zed ships with it wired up automatically when you open a folder containing Cargo.toml, and VS Code provides the official rust-analyzer extension.

You get inline inferred types (so you always know what type a complex iterator chain evaluates to), jump-to-definition right into standard library source code, and instant borrow-checker diagnostics as you type.

Here is my local Rust 1.100.1 toolchain running the fundamentals test suite we build across the first half of this handbook:

Terminal showing rustc 1.100.1, cargo 1.100.1, and cargo test running 16 unit tests and 1 doc test in 0.00s

Variables, types, and control flow

Rust is statically typed, with strong local type inference. You rarely spell out types on local variables, while function signatures always declare their parameter and return types explicitly so callers and the compiler have a clear contract.

Immutability, mut, constants, and shadowing

Variables in Rust are immutable by default. If you want to reassign or modify a variable, you opt in with mut:

let name = "Flavio";
let mut retries = 0;
retries += 1;

Making immutability the default cuts down on accidental state mutations. Whenever you see let mut, you immediately know that value changes later in the function.

Compile-time constants use const, require an explicit type annotation, and follow SCREAMING_SNAKE_CASE:

const MAX_CONCURRENCY: usize = 16;
const DEFAULT_TIMEOUT_SECS: u64 = 5;

Rust also allows shadowing: declaring a new variable with the same name using let. Unlike mut, shadowing lets you change the type while keeping the variable immutable afterward:

let port = "8080";
let port: u16 = port.trim().parse().expect("valid port");

Scalar types and numeric literals

Rust’s numeric types spell out their exact bit width and signedness, so an integer never quietly changes size between machines:

CategoryTypesNotes
Signed integersi8, i16, i32, i64, i128, isizei32 is the default integer type
Unsigned integersu8, u16, u32, u64, u128, usizeusize matches pointer width (indexes and lengths)
Floating pointf32, f64f64 is the default
Booleanbooltrue or false
Characterchar4-byte Unicode scalar value ('a', 'é', '€')

You can add underscores to numeric literals for readability and attach a type suffix directly to a literal when inference needs a hint:

let budget = 1_000_000u64;
let mask = 0xff_00u16;
let bits = 0b1010_0101u8;
let byte = b'A'; // u8 value 65

Integer overflow: checked, saturating, and wrapping

What happens if you add 10 to 250u8 (where u8 only goes up to 255)?

In debug builds, Rust panics immediately so you catch overflow bugs during testing. In release builds, Rust wraps around in two’s complement (250 + 10 = 4) for speed.

Whenever overflow is part of your logic (counters, billing math, byte parsing), make your intent explicit with the standard library’s overflow methods instead of relying on build mode:

pub fn safe_add(a: u8, b: u8) -> Option<u8> {
    a.checked_add(b)
}

pub fn clamped_sub(a: u8, b: u8) -> u8 {
    a.saturating_sub(b)
}

// checked_add(250, 10)    -> None
// saturating_sub(3, 10)   -> 0
// 250u8.wrapping_add(10)  -> 4
  • checked_* returns Option<T> (None on overflow).
  • saturating_* clamps at the type’s minimum or maximum bound.
  • wrapping_* wraps around predictably in both debug and release builds.

Type conversions: as vs TryFrom

Rust never converts numeric types implicitly. You cannot add a u16 and an i32 without choosing how to convert one of them.

The as keyword forces a raw cast, which silently truncates or wraps out-of-range values (-1i32 as u16 becomes 65535). For safe, fallible conversions from untrusted input, prefer TryFrom:

pub fn port_from_i32(raw: i32) -> Result<u16, String> {
    u16::try_from(raw).map_err(|_| format!("{raw} is outside 0..=65535"))
}

Passing -1 or 70_000 returns a clean Err instead of silently corrupting the port number.

For infallible widening conversions (like u16 to u32), use u32::from(port). The compiler guarantees no data can be lost.

Tuples, arrays, and destructuring

Two compound types live directly on the stack:

  • Tuples group a fixed number of mixed types.
  • Arrays hold a fixed number of values of one type ([T; N]).
let endpoint: (&str, u16) = ("127.0.0.1", 8080);
let (host, port) = endpoint; // destructuring
println!("{host}:{port} or {}:{}", endpoint.0, endpoint.1);

let codes: [u16; 3] = [200, 301, 404];
let zeros = [0u8; 16]; // 16 zeros on the stack

Indexing an array out of bounds (codes[9]) panics safely at runtime instead of reading arbitrary memory like C. If you want a checked lookup, call codes.get(9) which returns Option<&u16>.

Functions, statements, and expressions

Almost everything in Rust is an expression that evaluates to a value.

The last line of any block without a trailing semicolon is its value. You do not write return at the end of a function unless you are returning early:

fn add(a: i32, b: i32) -> i32 {
    a + b
}

Put a semicolon after a + b; and it turns into a statement evaluating to () (the unit type, Rust’s equivalent of void), which causes a compile error because the function promised an i32.

Even a plain { ... } block is an expression, which is handy for scoping temporary setup variables:

let total = {
    let subtotal = 4_900;
    let tax = subtotal / 10;
    subtotal + tax
};

if expressions and loops

Because if is an expression, you can bind its result directly (Rust has no ?: ternary operator):

let status = 200;
let label = if status < 400 { "ok" } else { "error" };

Both branches must return the same type.

Rust provides 3 loop keywords:

  • loop: repeats forever until break.
  • while: repeats while a condition stays true.
  • for: iterates cleanly over ranges and iterators without off-by-one bugs.
for n in 1..=5 {
    println!("step {n}");
}

Use 1..5 for an exclusive range (1, 2, 3, 4) and 1..=5 for an inclusive range (1, 2, 3, 4, 5).

Labeled loops and returning values from loop

Two small loop features make Rust code much cleaner than nested flag booleans.

First, break value returns a result directly from a loop:

let mut attempt = 0;
let token = loop {
    attempt += 1;
    if attempt == 3 {
        break "ready";
    }
};

Second, you can attach a label like 'outer: to a loop so break 'outer or continue 'outer exits nested loops cleanly:

pub fn find_in_grid(grid: &[&[i32]], target: i32) -> Option<(usize, usize)> {
    'outer: for (r, row) in grid.iter().enumerate() {
        for (c, &val) in row.iter().enumerate() {
            if val == target {
                return Some((r, c));
            }
            if val < 0 {
                break 'outer;
            }
        }
    }
    None
}

Strings, slices, and standard collections

Strings are the first place where Rust feels stricter than JavaScript or Python. That strictness comes from two real facts about computers: heap ownership and UTF-8 encoding.

String vs &str

Rust has two everyday string types:

  • String: an owned, heap-allocated, growable UTF-8 text buffer. Use it inside structs that own their fields, or whenever you build or mutate text.
  • &str (a string slice): a borrowed, read-only view into UTF-8 bytes stored somewhere else, such as a string literal baked into your binary ("hello") or a slice of a String.

Because &String automatically coerces to &str (through Deref coercion), write read-only function parameters as &str. Callers can then pass either "hello" or &my_string with zero allocation:

pub fn first_word(text: &str) -> &str {
    text.split_whitespace().next().unwrap_or("")
}

UTF-8 rules and why indexing fails

Both String and &str are guaranteed by the compiler and standard library to contain valid UTF-8.

In UTF-8, a single character can occupy 1 to 4 bytes. Look at "café €":

let s = "café €";
assert_eq!(s.len(), 9);          // 9 bytes in memory
assert_eq!(s.chars().count(), 6); // 6 Unicode scalar values
assert!(s.is_char_boundary(0));
assert!(!s.is_char_boundary(4)); // middle of the 2-byte 'é'

Because s[4] could land right in the middle of 'é', Rust forbids integer indexing on strings. Slicing by byte range (&s[0..4]) compiles, and panics at runtime if your index splits a multi-byte character.

When you need characters rather than raw bytes, iterate with .chars(), .char_indices(), or split with .split_whitespace() and .lines().

Building and formatting strings

You have three common ways to combine strings:

  • format!: builds a new String cleanly without moving the inputs (let msg = format!("{host}:{port}");).
  • push_str / push: appends to a mut String in place without allocating a second buffer (buf.push_str("\n");).
  • join: joins slices with a separator (["a", "b", "c"].join(", ")).

The + operator (a + &b) moves a and borrows b, which reads awkwardly once you combine more than two pieces. Reach for format! or push_str instead.

Avoiding allocations with Cow<'_, str>

Sometimes a function only needs to allocate a new String when input actually needs cleanup, and can return the original &str untouched 95% of the time.

std::borrow::Cow (“Clone on Write”) lets you return either a borrowed &str or an owned String from the same function:

use std::borrow::Cow;

pub fn normalize_slug(input: &str) -> Cow<'_, str> {
    if input.bytes().all(|b| b.is_ascii_lowercase() || b == b'-') {
        Cow::Borrowed(input)
    } else {
        Cow::Owned(input.to_lowercase().replace(' ', "-"))
    }
}

Calling normalize_slug("rust-handbook") allocates zero heap bytes (Cow::Borrowed), while normalize_slug("Rust Handbook") allocates and returns "rust-handbook" (Cow::Owned).

Vec<T> and slice patterns

Vec<T> is Rust’s growable heap array. Like &str is to String, a slice (&[T]) is a borrowed view into any contiguous sequence of T (a Vec<T>, an array [T; N], or part of either):

let mut tags = vec!["rust", "tokio"];
tags.push("axum");

for tag in &tags {
    println!("{tag}");
}

Notice we looped over &tags instead of tags. Looping over tags directly moves ownership into the loop and consumes the vector. Borrowing &tags lets you keep using tags afterward.

Slices come with great standard helpers like .windows(n) (sliding windows) and .chunks(n) (non-overlapping batches):

let nums = [10, 20, 30, 40];
let pairs: Vec<&[i32]> = nums.windows(2).collect();
// pairs == [&[10, 20], &[20, 30], &[30, 40]]

If you know roughly how many items you are going to push into a Vec, create it with Vec::with_capacity(n) to avoid repeated reallocations as it grows.

HashMap<K, V> and the entry API

HashMap<K, V> lives in std::collections::HashMap. Its .entry() API lets you look up, insert, or update a key in a single hash lookup.

Here is our verified count_words function from fundamentals/src/lib.rs:

use std::collections::HashMap;

pub fn count_words(text: &str) -> HashMap<String, usize> {
    let mut counts = HashMap::new();
    for word in text.split_whitespace() {
        let clean = word.to_lowercase();
        *counts.entry(clean).or_insert(0) += 1;
    }
    counts
}

.entry(clean).or_insert(0) returns a mutable reference (&mut usize) to the count for that word, inserting 0 first if missing. Then * dereferences it so we can increment it in place.

HashSet, BTreeMap, and VecDeque

Three more collections in std::collections cover almost every other data structure need:

CollectionOrdered?Best used for
HashSet<T>NoFast membership checks, deduplication, set unions and intersections
BTreeMap<K, V>Yes (sorted keys)Deterministic iteration order, range queries (range("a".."m"))
VecDeque<T>Insertion orderDouble-ended queues (push_back + pop_front in O(1))
use std::collections::{BTreeMap, HashSet, VecDeque};

let mut tags = HashSet::from(["rust", "axum"]);
tags.insert("rust"); // still length 2

let mut ordered = BTreeMap::new();
ordered.insert("z", 1);
ordered.insert("a", 2);
// iterating ordered yields ("a", 2) then ("z", 1)

let mut queue = VecDeque::from(["first", "second"]);
queue.push_back("third");
assert_eq!(queue.pop_front(), Some("first"));

Ownership, borrowing, and lifetimes

This is the chapter that makes Rust feel alien for the first week and wonderful for every year after.

Once you hold 4 simple rules in your head, the borrow checker stops feeling like an obstacle and starts feeling like a safety harness. Click through the interactive diagram below to see what happens on the stack and the heap at each step:

Fig 1 · 1/4How Rust tracks ownership, moves, and borrows at compile time
Step 1 · Own heap data on the stack

Stack vs heap memory

Fixed-size values whose size is known at compile time (i32, bool, [u8; 16], small structs) live directly on the stack. Allocating and freeing stack frames is nearly instant.

Growable or dynamically sized data (String, Vec<T>, HashMap<K, V>) stores its actual bytes on the heap, and keeps a small fixed-size header on the stack (for String, 24 bytes on 64-bit machines: a pointer to the heap buffer, the current byte length, and the allocated capacity).

Every heap value in Rust has one single owner. When that owner goes out of scope at the closing brace }, Rust automatically inserts a call to drop to free the heap memory. No GC pauses, no leaked buffers, no double-free bugs.

Move semantics and the Copy trait

When you assign a heap-owning value like a String to another variable, Rust moves ownership by copying only the 24-byte stack header and invalidating the old variable at compile time:

fn main() {
    let title = String::from("Rust Handbook");
    let moved = title;
    println!("Moved: {moved}");
    println!("Original: {title}"); // compile error!
}

Small, fixed-size stack types (i32, f64, bool, char, and tuples or structs made purely of Copy types) implement the Copy trait. Assigning let y = x; on an i32 copies the 4 bytes cheaply, so both x and y remain valid.

Heap types like String and Vec<T> never implement Copy. If you truly want a second independent copy on the heap, call .clone() explicitly so the allocation stays visible in code review.

Immutable borrows and exclusive mutable borrows

Most of the time you do not want to move or clone a value just to read or update it. You borrow it with a reference:

  • &T (shared / immutable borrow): you can have as many active &T readers at the same time as you want. Nobody can mutate the value while readers exist.
  • &mut T (exclusive / mutable borrow): you can have only one active &mut T writer at a time, with zero other readers or writers active.
  • No dangling references: the compiler guarantees a reference never outlives the value it points to.

Why does that rule matter so much? Because a data race requires two things at once: shared access AND mutation. By forbidding shared mutation at compile time, Rust eliminates iterator invalidation in single-threaded code and data races in multi-threaded code with one rule.

Three borrow-checker errors you will actually hit

Reading real rustc errors is the fastest way to build intuition. Here are the three borrow-checker errors every Rust developer sees in week one, compiled directly on Rust 1.100.1.

1. E0382: Use after move

Trying to read title after let moved = title; produces this diagnostic:

Terminal output showing rustc E0382 borrow of moved value diagnostic and clone suggestion

Fix: Borrow &title instead of moving it, or call title.clone() when you genuinely need two owned copies.

2. E0502: Mutable borrow while an immutable borrow is active

Suppose you hold a reference to the first element of a Vec and push a new item onto the vector:

fn main() {
    let mut scores = vec![10, 20, 30];
    let first = &scores[0];
    scores.push(40);
    println!("first = {first}");
}

Why is that dangerous? Because scores.push(40) might reallocate the Vec’s heap buffer to a brand-new address, leaving first pointing at freed memory! rustc catches it before the binary even exists:

error[E0502]: cannot borrow `scores` as mutable because it is also borrowed as immutable
 --> src/main.rs:4:5
  |
3 |     let first = &scores[0];
  |                  ------ immutable borrow occurs here
4 |     scores.push(40);
  |     ^^^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("first = {first}");
  |                        ----- immutable borrow later used here

Fix: Finish using first before calling scores.push(40), or copy the i32 value out (let first = scores[0];).

3. E0597: Borrowed value does not live long enough

Trying to return or store a reference to a variable that is about to be dropped:

fn main() {
    let r;
    {
        let temp = String::from("short lived");
        r = &temp;
    }
    println!("{r}");
}

rustc rejects the dangling pointer immediately:

error[E0597]: `temp` does not live long enough
 --> src/main.rs:5:13
  |
4 |         let temp = String::from("short lived");
  |             ---- binding `temp` declared here
5 |         r = &temp;
  |             ^^^^^ borrowed value does not live long enough
6 |     }
  |     - `temp` dropped here while still borrowed
7 |     println!("{r}");
  |                - borrow later used here

Fix: Return an owned String instead of a reference to a local variable, or declare temp in the outer scope.

Non-lexical lifetimes and partial moves

Modern Rust uses non-lexical lifetimes (NLL), meaning a borrow ends right after its last use rather than waiting for the closing brace }:

let mut notes = String::from("draft");
let preview = &notes;
println!("{preview}"); // last use of `preview` ends the shared borrow

notes.push_str(" v2"); // mutable borrow is allowed immediately

Rust also tracks disjoint struct fields independently. If a struct has two fields user.name and user.email, you can borrow &user.name and &mut user.email at the same time, or even move user.name out while still reading user.email (a partial move).

Lifetimes in functions and structs

Sometimes a function takes two borrowed references and returns one of them. The compiler needs to know which input the returned reference is tied to so it can prove the return value will not outlive its source.

That is all a lifetime annotation ('a) does. It describes the relationship between reference scopes for the compiler without changing how long any value lives:

pub fn longest<'a>(left: &'a str, right: &'a str) -> &'a str {
    if left.len() >= right.len() {
        left
    } else {
        right
    }
}

Reading 'a aloud: “the returned &str is valid for as long as both left and right remain valid.”

Structs can hold borrowed references too, which lets parsers slice straight into an existing buffer with zero heap allocations. Here is our verified LogLine<'a> parser from fundamentals/src/ownership_and_lifetimes.rs:

#[derive(Debug, PartialEq)]
pub struct LogLine<'a> {
    pub level: &'a str,
    pub message: &'a str,
}

impl<'a> LogLine<'a> {
    pub fn parse(raw: &'a str) -> Option<Self> {
        let (level, message) = raw.split_once(": ")?;
        Some(Self { level, message })
    }
}

The <'a> tells the compiler that a LogLine<'a> cannot outlive the raw string buffer it borrowed from.

Rule of thumb for real apps: use owned fields (String, Vec<T>) in domain structs like User or Invoice so you stay free of lifetime parameters, and reach for borrowed structs like LogLine<'a> when writing parsers or hot-path code where avoiding allocations matters.

Lifetime elision and the 'static myth

You write explicit 'a annotations far less often than Rust’s reputation suggests, because the compiler applies lifetime elision rules automatically:

  1. Every input reference gets its own lifetime.
  2. If there is only one input reference, the output reference automatically gets that lifetime (fn first_word(text: &str) -> &str).
  3. If a method takes &self or &mut self, the output reference gets self’s lifetime.

One more misconception trips up beginners: T: 'static is a bound about ownership, rather than read-only globals.

A string literal (&'static str) does live for the entire program. But a trait bound like T: 'static (required by thread::spawn and tokio::spawn) simply means “T owns all its data and holds no temporary non-'static references.” An owned String created two milliseconds ago satisfies T: 'static, because whoever holds it can keep it as long as they want without risking a dangling pointer.

Structs, enums, and pattern matching

Rust has no classes and no inheritance. Instead, you compose structs (data), impl blocks (behavior), enums (tagged unions), and traits (shared contracts).

Named structs, tuple structs, and unit structs

Most structs have named fields:

#[derive(Debug, Clone, PartialEq)]
pub struct Invoice {
    pub customer: String,
    pub cents: u64,
    pub paid: bool,
}

Rust also has two compact struct forms:

  • Tuple structs wrap unnamed fields, ideal for type-safe IDs (struct UserId(u64); struct OrderId(u64);) so you can never accidentally pass an OrderId to a function expecting a UserId.
  • Unit structs hold no fields at all (struct HandleInertiaRequests;) and are useful for stateless marker types or trait implementations.

Methods, associated functions, and self forms

You attach methods to a struct inside an impl block:

impl Invoice {
    pub fn new(customer: impl Into<String>, cents: u64) -> Self {
        Self {
            customer: customer.into(),
            cents,
            paid: false,
        }
    }

    pub fn mark_paid(&mut self) {
        self.paid = true;
    }

    pub fn euros(&self) -> f64 {
        self.cents as f64 / 100.0
    }
}

Notice the three ways a method receives self:

  • &self: borrows the struct read-only (euros).
  • &mut self: borrows the struct mutably (mark_paid).
  • self: takes ownership and consumes the struct (great for builders or closing a connection handle so it cannot be reused).

Functions inside impl without a self parameter (like Invoice::new) are associated functions, called with ::.

Deriving standard traits

Writing #[derive(Debug, Clone, PartialEq)] above a struct or enum asks the compiler to generate boilerplate trait implementations automatically.

When every field is Copy (for instance struct Point { x: f64, y: f64 }), you can add Copy too. Adding Default lets you construct structs with fallback values using struct update syntax:

#[derive(Debug, Default)]
struct ServerConfig {
    host: String,
    port: u16,
}

let cfg = ServerConfig {
    port: 8080,
    ..Default::default()
};

Enums with data

Enums in Rust are algebraic data types (tagged unions). Each variant can carry completely different fields, or no fields at all:

#[derive(Debug, PartialEq)]
pub enum Payment {
    Cash(u64),
    Card { last4: String, cents: u64 },
    Refunded,
}

impl Payment {
    pub fn describe(&self) -> String {
        match self {
            Payment::Cash(cents) => {
                format!("cash: {:.2} EUR", *cents as f64 / 100.0)
            }
            Payment::Card { last4, cents } => {
                format!("card ****{last4}: {:.2} EUR", *cents as f64 / 100.0)
            }
            Payment::Refunded => "refunded".to_string(),
        }
    }
}

This lets you make invalid states unrepresentable. A Payment::Refunded literally cannot carry a stale last4 card number, and a Payment::Card always has both last4 and cents.

Exhaustive match, ranges, guards, and @ bindings

match is exhaustive. If you add a Payment::BankTransfer variant six months from now, rustc flags every match expression in the entire codebase that forgot to handle it.

Patterns inside match also support | alternatives, inclusive ranges (200..=299), @ bindings to capture a matched value, and if guards for extra conditions:

pub fn classify_http_status(code: u16, retry_enabled: bool) -> &'static str {
    match code {
        200..=299 => "success",
        300..=399 => "redirect",
        400 | 422 => "bad_input",
        401 | 403 => "auth_error",
        404 => "not_found",
        c @ 500..=599 if retry_enabled && c != 501 => "retryable_server_error",
        500..=599 => "server_error",
        _ => "other",
    }
}

The _ wildcard arm matches anything left over. Use it carefully: matching variants explicitly without _ is better when you want the compiler to alert you about new enum variants later.

if let, let...else, and matches!

When you only care about one variant, a full match adds noise. Rust gives you three clean shortcuts:

// 1. Run code only for one variant
if let Payment::Cash(cents) = payment {
    println!("Cash payment of {cents} cents");
}

// 2. Unwrap or return early (keeps the happy path unindented)
let Payment::Card { last4, .. } = payment else {
    return;
};
println!("Card ending in {last4}");

// 3. Boolean pattern check
let is_refund = matches!(payment, Payment::Refunded);

let ... else is one of the best ergonomics upgrades in modern Rust. It lets you handle error or None branches early and keep the rest of your function flat.

Error handling with Option, Result, and ?

Rust has no null and no try/catch exceptions. Both absence and failure are ordinary enums in the standard library, so the compiler checks them just like any other type.

Click through the diagram below to see how Option, Result, and ? work together:

Fig 2 · 1/3How Option, Result, and the ? operator handle errors in Rust
Step 1 · Option<T> makes missing values explicit

Option<T> and its combinators

Whenever a value might be absent (looking up a key in a HashMap, finding a row in SQLite, reading the first word of a string), Rust returns Option<T>:

enum Option<T> {
    Some(T),
    None,
}

You cannot accidentally dereference None and crash with a null-pointer exception. Besides match and if let, Option ships with concise combinators that eliminate nested if blocks:

let env_port: Option<String> = std::env::var("PORT").ok();

let port: u16 = env_port
    .as_deref()                   // Option<&str>
    .and_then(|s| s.parse().ok()) // Option<u16>
    .unwrap_or(3000);             // u16 fallback
  • .map(f) transforms the inner value when Some.
  • .and_then(f) chains another operation that itself returns an Option.
  • .unwrap_or(default) returns a fallback value, and .unwrap_or_else(|| compute()) runs a closure lazily only when None.
  • .ok_or_else(|| err) converts an Option<T> into a Result<T, E> so you can propagate it with ?.

You can also use ? directly inside any function that returns Option<T>, as we did in LogLine::parse:

let (level, message) = raw.split_once(": ")?;

If split_once returns None, the function returns None immediately.

Result<T, E> and propagating errors with ?

Whenever an operation can fail (parsing input, opening a file, sending an HTTP request), it returns Result<T, E>:

enum Result<T, E> {
    Ok(T),
    Err(E),
}

Here is our verified parse_port function from fundamentals/src/lib.rs:

pub fn parse_port(raw: &str) -> Result<u16, String> {
    let port: u16 = raw
        .trim()
        .parse()
        .map_err(|_| format!("invalid port number: {raw}"))?;

    if port == 0 {
        return Err("port 0 is reserved".to_string());
    }

    Ok(port)
}

The ? operator at the end of .map_err(...) does two things:

  1. If the result is Ok(value), it unwraps value and assigns it to port.
  2. If the result is Err(err), it converts err through the From trait (if needed) and returns Err(...) immediately to the caller.

Converting error types with map_err and From

A real function often calls three different libraries that each return their own error type (std::io::Error, serde_json::Error, sqlx::Error).

When your function returns a custom error enum AppError, implementing From<std::io::Error> for AppError lets ? convert I/O errors automatically without cluttering your logic with .map_err(...) on every line.

Structured errors with thiserror

Writing Display and From implementations by hand for every error enum gets tedious. The thiserror crate generates them at compile time with zero runtime overhead:

use thiserror::Error;

#[derive(Debug, Error)]
pub enum ApiError {
    #[error("validation error: {0}")]
    Validation(String),

    #[error("service not found: {0}")]
    NotFound(String),

    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),
}

#[from] generates impl From<sqlx::Error> for ApiError, so every SQLx query inside an Axum handler can end with ?. Use thiserror in libraries and web APIs where callers or response mappers need to inspect specific failure variants.

Quick application errors with anyhow

When writing a small CLI script or internal tool where callers only need to print a human-readable error chain and exit, anyhow saves even more boilerplate:

use anyhow::{Context, Result};

fn load_config(path: &str) -> Result<String> {
    std::fs::read_to_string(path)
        .with_context(|| format!("failed to read config file {path}"))
}

anyhow::Result<T> accepts any error type that implements std::error::Error, and .with_context(...) wraps low-level OS errors (“No such file or directory”) with the exact file path that failed.

When panic!, unwrap, and expect belong

Calling panic!, .unwrap(), or .expect("reason") aborts the current thread immediately.

Keep .unwrap() and .expect() in tests, quick prototypes, and invariants that are mathematically impossible to violate (like compiling a hardcoded regex literal). In production web handlers or CLI input parsing, always return Result and propagate with ? so bad input produces a clean 422 or error message instead of crashing a task.

Generics, traits, closures, and iterators

Once you understand structs and enums, traits and iterators are what turn Rust from verbose into remarkably expressive, without giving up native speed.

Writing generic functions and structs

Generics let you write one function or container that works across any type T:

pub struct Wrapper<T>(pub T);

fn pick_first<T>(a: T, _b: T) -> T {
    a
}

Rust compiles generics via monomorphization. When you call pick_first with i32 and with String, rustc generates specialized machine code for both types at compile time. There is zero boxing and zero runtime indirection.

Defining and implementing traits

A trait defines shared behavior, similar to an interface in Go or TypeScript, with one major advantage: you can implement your own trait on any type, even types from external crates or the standard library.

pub trait Summary {
    fn summary(&self) -> String;

    // Default method implementation that types can override
    fn preview(&self) -> String {
        format!("[SUMMARY] {}", self.summary())
    }
}

impl Summary for Invoice {
    fn summary(&self) -> String {
        let state = if self.paid { "paid" } else { "open" };
        format!("{} ({:.2} EUR, {state})", self.customer, self.euros())
    }
}

Trait bounds, where clauses, and associated types

Constrain generic parameters by naming the traits they must implement. For short bounds, inline syntax reads cleanly:

pub fn format_item<T: Summary>(item: &T) -> String {
    format!("[SUMMARY] {}", item.summary())
}

When a function takes several generic parameters with multiple bounds, move the bounds into a where clause so the signature stays readable:

pub fn apply_twice<F>(x: i32, mut f: F) -> i32
where
    F: FnMut(i32) -> i32,
{
    let first = f(x);
    f(first)
}

When a trait naturally has one output type per implementation (like an iterator’s element type or a repository’s record type), use an associated type (type Item;) instead of a generic parameter on the trait:

pub trait Repository {
    type Item;
    fn find(&self, id: usize) -> Option<&Self::Item>;
}

pub struct MemoryRepo<T> {
    items: Vec<T>,
}

impl<T> Repository for MemoryRepo<T> {
    type Item = T;

    fn find(&self, id: usize) -> Option<&Self::Item> {
        self.items.get(id)
    }
}

Essential standard traits: Display, FromStr, From, Default

A small group of standard traits shows up across almost every Rust crate:

TraitPurposeTypical usage
DebugDeveloper formatting ({:?})#[derive(Debug)] on nearly every type
DisplayUser-facing formatting ({})Implementing .to_string() and human output
FromStrParsing text into a typeEnables "127.0.0.1:8080".parse::<HostPort>()
From / IntoInfallible conversionsPowers ? error conversion and flexible arguments
TryFrom / TryIntoFallible conversionsSafe integer/string narrowing
DefaultSensible fallback valueStruct update syntax ..Default::default()
Send / SyncThread-safety markersAuto-derived by the compiler for concurrency

Here is our verified HostPort type implementing both Display and FromStr in fundamentals/src/traits_and_iterators.rs:

use std::fmt;
use std::str::FromStr;

#[derive(Debug, PartialEq)]
pub struct HostPort {
    pub host: String,
    pub port: u16,
}

impl fmt::Display for HostPort {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}:{}", self.host, self.port)
    }
}

impl FromStr for HostPort {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (host, port_str) = s
            .split_once(':')
            .ok_or_else(|| format!("expected host:port, got {s}"))?;
        let port = port_str
            .parse::<u16>()
            .map_err(|_| format!("invalid port in {s}"))?;
        Ok(Self {
            host: host.to_string(),
            port,
        })
    }
}

Once FromStr is implemented, "127.0.0.1:8080".parse::<HostPort>() works automatically, and implementing Display gives you .to_string() for free.

Static dispatch (impl Trait) vs dynamic dispatch (dyn Trait)

Rust lets you choose explicitly between zero-cost static dispatch and flexible dynamic dispatch:

  • Static dispatch (fn print(item: &impl Summary) or <T: Summary>): monomorphized at compile time. Fastest runtime execution and allows inlining, at the cost of slightly larger binaries if called with many concrete types.
  • Dynamic dispatch (Vec<Box<dyn Summary>> or &dyn Summary): uses a vtable pointer at runtime. Necessary whenever you need one collection holding different concrete types that all implement Summary (like a list of heterogeneous plugins or middleware layers).

Default to static dispatch (impl Trait or generics) until you genuinely need heterogeneous collections or want to reduce compile-time monomorphization bloat.

The orphan rule and the newtype pattern

Rust enforces the orphan rule: you can implement a trait for a type only if either the trait OR the type is defined inside your own crate.

That prevents two unrelated crates from implementing Display for Vec<String> in conflicting ways. When you really need to implement an external trait on an external type, wrap it in a zero-cost tuple struct (the newtype pattern):

struct PrettyList(Vec<String>);

impl std::fmt::Display for PrettyList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0.join(", "))
    }
}

At runtime, PrettyList has zero memory overhead compared to Vec<String>.

Closures: Fn, FnMut, and FnOnce

Closures are anonymous functions written with vertical pipes: |x| x * 2. They capture variables from their surrounding scope automatically using the least restrictive mode needed:

  1. Fn: borrows captured variables immutably. Can be called concurrently many times.
  2. FnMut: borrows captured variables mutably (for instance incrementing a counter calls += 1). Can be called sequentially, one call at a time.
  3. FnOnce: takes ownership of captured variables (moving or dropping them). Can only be called once.

Adding move before the pipes (move || ...) forces the closure to take ownership of everything it captures, which is required whenever you hand a closure to a new thread or async task.

One subtle borrow-checker lesson I hit while writing apply_twice for this handbook: writing f(f(x)) on a mut f: F where F: FnMut(i32) -> i32 fails with E0499 (“cannot borrow f as mutable more than once at a time”), because the outer call borrows f before the inner f(x) finishes. Splitting it into let first = f(x); f(first) makes the two sequential borrows obvious to the compiler.

Iterators: .iter(), .iter_mut(), and .into_iter()

Every Rust collection gives you three ways to iterate, matching Rust’s three ownership modes:

MethodItem yieldedCollection usable afterward?
.iter()&T (shared borrow)Yes
.iter_mut()&mut T (mutable borrow)Yes (with mutated items)
.into_iter()T (owned value)No (consumed)

A for x in &vec loop calls .iter(), for x in &mut vec calls .iter_mut(), and for x in vec calls .into_iter().

Common iterator combinators

Iterators in Rust are lazy and zero-cost. Chaining combinators compiles down to the same tight loop you would write in C, with no intermediate temporary vectors allocated along the way:

// Filter + transform + sum
let evens_sum: i32 = (1..=10)
    .filter(|n| n % 2 == 0)
    .map(|n| n * n)
    .sum();
assert_eq!(evens_sum, 220);

// Parse valid integers and skip malformed entries in one pass
let raw = ["10", "bad", "20", "30"];
let valid_sum: i32 = raw
    .iter()
    .filter_map(|s| s.parse::<i32>().ok())
    .sum();
assert_eq!(valid_sum, 60);

// Accumulate multiple values in a single pass with fold
let (sum, count) = [10, 20, 30, 40]
    .iter()
    .fold((0, 0), |(s, c), &n| (s + n, c + 1));
assert_eq!((sum, count), (100, 4));

Also worth keeping in your back pocket: .enumerate() (yields (index, item)), .zip(other) (pairs two iterators together), .flat_map(f) (maps and flattens nested iterators), and .collect::<Result<Vec<_>, _>>() (short-circuits on the first Err in a sequence of Results!).

Implementing Iterator on your own type

Any struct can plug into the entire standard library iterator ecosystem by implementing one method: next(&mut self) -> Option<Self::Item>:

pub struct Countdown {
    current: u32,
}

impl Countdown {
    pub fn new(start: u32) -> Self {
        Self { current: start }
    }
}

impl Iterator for Countdown {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current == 0 {
            None
        } else {
            let value = self.current;
            self.current -= 1;
            Some(value)
        }
    }
}

// Automatically gains .collect(), .map(), .filter(), .take(), .sum(), etc.
let seq: Vec<u32> = Countdown::new(3).collect(); // [3, 2, 1]

Smart pointers, interior mutability, and RAII

Regular references (&T and &mut T) only borrow data. Smart pointers own the data they point to and carry extra capabilities like heap allocation, reference counting, or automatic cleanup.

Box<T> for heap allocation and recursive types

Box<T> allocates a value on the heap and keeps a single pointer to it on the stack. When the Box goes out of scope, both the pointer and the heap value drop cleanly.

You reach for Box<T> in 3 situations:

  1. Recursive types like trees or linked lists (enum Node { Leaf(i32), Branch(Box<Node>, Box<Node>) }), where the compiler needs a known fixed size on the stack.
  2. Trait objects (Box<dyn Error>, Box<dyn Summary>).
  3. Large structs you want to move around cheaply by transferring an 8-byte pointer instead of copying kilobytes on the stack.

Deref coercion and custom Drop cleanup (RAII)

Two traits explain most of Rust’s smart-pointer ergonomics:

  • Deref: lets a wrapper type behave like a reference to its inner value. That is why &String automatically coerces to &str, &Vec<T> coerces to &[T], and calling wrapped.len() on our Wrapper(String::from("rust")) works transparently:
use std::ops::Deref;

pub struct Wrapper<T>(pub T);

impl<T> Deref for Wrapper<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
  • Drop: runs automatically when a value goes out of scope (in reverse declaration order). This pattern, known as RAII (Resource Acquisition Is Initialization), is how Rust closes files, releases mutex locks, drops semaphore permits, and resets temporary state even on early returns or panics.

Here is a verified RAII guard (TempFlag) from fundamentals/src/ownership_and_lifetimes.rs that sets a flag on entry and guarantees it resets on exit:

use std::cell::Cell;

pub struct TempFlag<'a> {
    flag: &'a Cell<bool>,
}

impl<'a> TempFlag<'a> {
    pub fn enter(flag: &'a Cell<bool>) -> Self {
        flag.set(true);
        Self { flag }
    }
}

impl Drop for TempFlag<'_> {
    fn drop(&mut self) {
        self.flag.set(false);
    }
}

If you need to release a value early before the end of a block (such as dropping a MutexGuard before an .await or releasing a file handle), call std::mem::drop(guard).

Rc<T> for single-threaded shared ownership

Sometimes one graph node or configuration string needs multiple owners within a single thread. Rc<T> (“Reference Counted”) tracks how many handles point to the heap value and frees it when the count drops to zero:

use std::rc::Rc;

let config = Rc::new(String::from("production"));
let copy_a = Rc::clone(&config);
let copy_b = Rc::clone(&config);
assert_eq!(Rc::strong_count(&config), 3);

Rc::clone(&config) increments an integer reference counter without copying the underlying string bytes. Because that counter is non-atomic, Rc<T> is fast and strictly single-threaded (rustc blocks sending it to another thread).

Interior mutability with Cell<T> and RefCell<T>

Occasionally you need to mutate data inside a structure even when you only hold an immutable &self reference (such as a cache, test spy, or reference-counted graph node).

Rust provides two single-threaded interior mutability wrappers:

  • Cell<T>: for small Copy values (bool, usize). Lets you .get() and .set() with zero runtime overhead because values are copied in and out rather than borrowed.
  • RefCell<T>: for non-Copy values like Vec<T> or String. Moves Rust’s borrowing rule (“many readers OR one writer”) from compile time to runtime. Violating it (calling .borrow_mut() while another .borrow() is still alive) panics cleanly instead of corrupting memory:
use std::cell::RefCell;

let log = RefCell::new(Vec::new());
log.borrow_mut().push("started");
log.borrow_mut().push("ready");
assert_eq!(log.borrow().len(), 2);

Choosing the right smart pointer

Use this flowchart whenever regular stack ownership is not enough:

Choosing a Rust smart pointerDecision flowchart for picking between Box, Rc, RefCell, Arc, and Arc with Mutex or RwLock.Single owner,heap or recursiveShared in onethreadRead-onlyRead and writeShared acrossthreadsRead-onlyRead and writeNeed heap orsharedownership?Box of TNeed mutation?Rc of TRc of RefCellof TNeed mutation?Arc of TArc of Mutex orRwLock
TypeThread-safe?OverheadCommon use case
Box<T>Same as TSingle heap allocRecursive types, trait objects (Box<dyn Error>)
Rc<T>NoNon-atomic countShared read-only data within one thread
RefCell<T>NoRuntime borrow checkInterior mutability in single-threaded code
Arc<T>Yes (Send + Sync)Atomic ref countSharing config, HTTP clients, or pools across threads
Arc<Mutex<T>>YesAtomic count + lockShared mutable state across threads

Threads, channels, and shared-state concurrency

Rust calls its concurrency story “fearless concurrency” for a concrete reason: data races fail to compile.

Spawning OS threads with move closures

std::thread::spawn starts a real OS thread. Because the spawned thread might outlive the current stack frame, its closure must be 'static, which usually means adding move to transfer ownership of any captured values:

use std::thread;

let msg = String::from("hello from worker");
let handle = thread::spawn(move || {
    println!("{msg}");
});

handle.join().expect("thread panicked");

Scoped threads: borrowing stack data safely

What if you want to split a local slice across two threads, compute a parallel sum, and immediately join both threads without wrapping your slice in an Arc?

std::thread::scope guarantees that every thread spawned inside the scope finishes before scope returns, so the compiler safely lets worker threads borrow local stack data directly!

Here is our verified scoped_parallel_sum from fundamentals/src/concurrency_and_macros.rs:

use std::thread;

pub fn scoped_parallel_sum(numbers: &[i64]) -> i64 {
    let mid = numbers.len() / 2;
    let (left, right) = numbers.split_at(mid);

    thread::scope(|s| {
        let h1 = s.spawn(|| left.iter().sum::<i64>());
        let h2 = s.spawn(|| right.iter().sum::<i64>());
        h1.join().unwrap() + h2.join().unwrap()
    })
}

Zero heap allocations, zero Arc, zero cloning, and 100% compile-time lifetime checked.

Message passing with std::sync::mpsc

When threads coordinate by sending work items or results to each other, channels keep ownership clear. std::sync::mpsc gives you a multi-producer, single-consumer channel:

use std::sync::mpsc;
use std::thread;

let (tx, rx) = mpsc::channel();

for i in 1..=3 {
    let tx = tx.clone();
    thread::spawn(move || tx.send(i * 10).unwrap());
}
drop(tx); // drop the original sender so `rx` knows when all producers finish

let mut received: Vec<i32> = rx.iter().collect();
received.sort();
assert_eq!(received, vec![10, 20, 30]);

Remember that drop(tx) line! Because the original tx stays alive in the main thread, rx.iter() would wait forever unless you drop the extra handle once all worker threads have their own clones.

Shared mutable state with Arc<Mutex<T>>

When multiple threads must read and update shared state, combine Arc<T> (atomic reference counting) with Mutex<T>:

use std::sync::{Arc, Mutex};
use std::thread;

pub fn parallel_counter(threads: usize, increments: usize) -> usize {
    let counter = Arc::new(Mutex::new(0usize));
    let mut handles = Vec::with_capacity(threads);

    for _ in 0..threads {
        let shared = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..increments {
                let mut guard = shared.lock().expect("mutex poisoned");
                *guard += 1;
            }
        }));
    }

    for handle in handles {
        handle.join().expect("thread panicked");
    }

    *counter.lock().expect("mutex poisoned")
}

Look closely at Mutex<T> in Rust compared to C or Go. In Rust, the Mutex owns the protected 0usize inside it. It is impossible to accidentally read or mutate the data without holding the lock, and the lock unlocks automatically the instant guard drops at the end of the inner loop.

Read-heavy state with RwLock and lock-free Atomics

Two more primitives in std::sync fit common workloads even better than Mutex:

  • RwLock<T>: allows many concurrent readers (.read()) OR one exclusive writer (.write()). Ideal for in-memory configuration or routing tables read thousands of times per second and updated rarely.
  • AtomicUsize / AtomicBool: lock-free CPU atomic instructions for simple counters, metrics, and shutdown flags:
use std::sync::RwLock;
use std::sync::atomic::{AtomicUsize, Ordering};

let cache = RwLock::new(String::from("v1"));
{
    let r1 = cache.read().unwrap();
    let r2 = cache.read().unwrap(); // multiple readers allowed together
    assert_eq!(*r1, *r2);
}
*cache.write().unwrap() = String::from("v2");

let hits = AtomicUsize::new(0);
hits.fetch_add(1, Ordering::Relaxed);
assert_eq!(hits.load(Ordering::Relaxed), 1);

Send and Sync: why data races won’t compile

Rust’s compiler enforces thread safety through two automatic marker traits:

  • Send: safe to transfer ownership of a value to another thread. Almost all types are Send, except single-threaded pointers like Rc<T>.
  • Sync: safe to share an immutable reference (&T) across threads simultaneously (T is Sync if &T is Send). RefCell<T> and Cell<T> are NOT Sync, while Mutex<T>, RwLock<T>, and AtomicUsize are.

If you accidentally try to pass an Rc<RefCell<Vec<u8>>> into thread::spawn, rustc refuses to compile right away instead of letting you ship a subtle race condition.

Modules, Cargo workspaces, files, and serde

Once a program grows past a single file, knowing how Cargo structures modules, workspaces, file I/O, and JSON serialization saves hours of friction.

Modules, files, and pub vs pub(crate)

Everything inside a Rust module is private by default. You declare submodules with mod and expose only the API you want callers to depend on:

  • pub: visible everywhere, including external crates.
  • pub(crate): visible across your own crate, hidden from external callers.
  • pub(super): visible only to the parent module.

A module named mod payments; looks for either src/payments.rs or src/payments/mod.rs. Prefer the modern src/payments.rs + src/payments/stripe.rs layout so you don’t end up with twenty editor tabs all named mod.rs.

Splitting src/lib.rs and src/main.rs

For any non-trivial CLI or server, put your domain types, handlers, and business logic in src/lib.rs, and keep src/main.rs as a thin 30-line bootstrap that parses env vars or CLI flags and calls into the library.

That split unlocks clean integration tests in tests/ (which import your library crate just like an external user) and lets you test an Axum router in memory without opening a TCP port.

Cargo workspaces and shared dependencies

When a repository contains multiple related crates (such as a shared core library, a CLI tool, and a web API), group them into a Cargo workspace. Every member shares one Cargo.lock and one target/ cache, so shared dependencies like tokio and serde compile only once.

Here is the exact workspace Cargo.toml powering all the verified code in this handbook:

[workspace]
resolver = "3"
members = ["fundamentals", "urlprobe", "pulseapi"]

[workspace.package]
edition = "2024"
version = "0.1.0"

Member crates inherit workspace metadata with version.workspace = true and edition.workspace = true.

Working with Path, PathBuf, and std::fs

Just as Rust splits strings into borrowed &str and owned String, filesystem paths come in two matching types inside std::path:

  • &Path: a borrowed path slice (use this for function parameters).
  • PathBuf: an owned, mutable path (use .join(...) so path separators work properly across macOS, Linux, and Windows).
use std::path::{Path, PathBuf};

pub fn join_config_path(base: &Path) -> PathBuf {
    base.join("config").join("app.toml")
}

For small config files, std::fs::read_to_string(path) and std::fs::write(path, bytes) read or write the entire file in one line.

Buffered file I/O with BufReader and BufWriter

For large logs or line-by-line processing, reading the whole file into memory is wasteful and unbuffered single-byte syscalls are slow. Wrap File in BufReader and BufWriter:

use std::fs::File;
use std::io::{self, BufRead, BufReader, BufWriter, Write};
use std::path::Path;

pub fn count_matching_lines(path: &Path, needle: &str) -> io::Result<usize> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    let mut matches = 0;
    for line in reader.lines() {
        if line?.contains(needle) {
            matches += 1;
        }
    }
    Ok(matches)
}

pub fn write_lines(path: &Path, lines: &[&str]) -> io::Result<()> {
    let file = File::create(path)?;
    let mut writer = BufWriter::new(file);
    for line in lines {
        writeln!(writer, "{line}")?;
    }
    writer.flush()
}

Always call writer.flush() at the end of write_lines so any buffered write errors surface as an io::Result instead of being silently ignored during Drop.

JSON serialization with serde and tagged enums

serde + serde_json is the gold standard for serialization in Rust. Deriving Serialize and Deserialize generates fast, zero-reflection encoders and decoders at compile time.

Where serde really shines is mapping messy real-world JSON payloads (like Stripe or GitHub webhooks) straight into typed Rust enums using attributes:

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum WebhookEvent {
    OrderPaid {
        order_id: u64,
        #[serde(default)]
        currency: String,
    },
    RefundIssued {
        order_id: u64,
        reason: String,
    },
}

Now parsing {"type":"order_paid","order_id":42} with serde_json::from_str::<WebhookEvent>(raw)? automatically matches WebhookEvent::OrderPaid and fills missing currency with an empty string! Other handy attributes include #[serde(rename = "camelCaseField")], #[serde(skip_serializing_if = "Option::is_none")], and #[serde(flatten)] for merging shared metadata structs.

Testing, Clippy, macros, and unsafe Rust

Rust ships a complete quality toolchain right out of the box, plus two advanced tools you will eventually encounter in real codebases: macros and unsafe.

Unit tests inside #[cfg(test)]

Put unit tests right at the bottom of any module inside #[cfg(test)] mod tests. The #[cfg(test)] attribute ensures Cargo only compiles test code during cargo test (zero bloat in production binaries), and tests inside the module can inspect private functions too:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn overflow_and_try_from() {
        assert_eq!(safe_add(250, 10), None);
        assert_eq!(clamped_sub(3, 10), 0);
        assert_eq!(port_from_i32(8080), Ok(8080));
        assert!(port_from_i32(-1).is_err());
    }
}

You can also return Result<(), Box<dyn std::error::Error>> from a #[test] function so you can use ? instead of .unwrap(), and annotate expected failure tests with #[should_panic(expected = "out of bounds")].

Integration tests and doc tests

Beyond unit tests, Cargo natively runs two more layers:

  • Integration tests in top-level tests/*.rs files compile each file as a separate crate testing only your pub API.
  • Doc tests inside /// documentation comments compile and execute every code block during cargo test, so examples in your docs can never drift out of sync with the code:
/// Returns the first whitespace-separated word of `text` as a borrowed slice.
///
/// # Examples
///
/// ```
/// assert_eq!(fundamentals::first_word("hello rust"), "hello");
/// assert_eq!(fundamentals::first_word("single"), "single");
/// ```
pub fn first_word(text: &str) -> &str {
    text.split_whitespace().next().unwrap_or("")
}

For large workspaces, cargo nextest run is a popular drop-in parallel test runner with cleaner output and per-test timeouts. For a broader look at structuring test suites and CI pipelines, see my Testing, Debugging & CI/CD Handbook.

Strict linting with Clippy and rustfmt

Run these two commands in CI on every project:

cargo fmt --check
cargo clippy --workspace --all-targets -- -D warnings

Clippy catches hundreds of subtle issues: redundant .clone() calls, unnecessary .fold() chains that can be .sum(), redundant match guards, holding a lock across an .await, and unused imports. Passing -- -D warnings turns every warning into a hard error, which is especially helpful when coding agents edit your repo.

Declarative macros with macro_rules!

You already used built-in macros like println!, vec!, and format!. Unlike C preprocessor macros (which do blind text substitution), Rust’s macro_rules! macros operate on parsed token trees and stay hygienic (variables declared inside a macro never collide with variables outside).

Here is a verified declarative macro (string_map!) from fundamentals/src/concurrency_and_macros.rs that builds a HashMap<String, V> cleanly:

#[macro_export]
macro_rules! string_map {
    ($($key:expr => $val:expr),* $(,)?) => {{
        let mut map = ::std::collections::HashMap::new();
        $(
            map.insert($key.to_string(), $val);
        )*
        map
    }};
}

let versions = string_map! {
    "rust" => 2024,
    "go" => 127,
};

Look at the pattern ($($key:expr => $val:expr),* $(,)?): it matches zero or more key => val pairs separated by commas, with an optional trailing comma $(,)?.

Derive and attribute proc macros

When you write #[derive(Serialize, Parser)] or #[tokio::main], you are invoking procedural macros (separate Rust crates that receive a token stream of your struct or function at compile time and emit generated Rust code).

You rarely need to write proc macros yourself for application code, and understanding what they do explains why Rust code with serde, clap, thiserror, tokio, and axum stays so concise while remaining 100% statically typed.

What unsafe Rust actually allows (and how to isolate it)

A common myth is that unsafe { ... } turns off the borrow checker. It does not! Every normal ownership and borrow check still runs inside an unsafe block.

unsafe unlocks exactly 5 low-level operations the compiler cannot verify on its own:

  1. Dereferencing a raw pointer (*const T, *mut T).
  2. Calling an unsafe function or foreign C function (extern "C" FFI).
  3. Accessing or modifying a mutable static variable.
  4. Implementing an unsafe trait (such as manually promising a custom pointer is Send or Sync).
  5. Reading fields of a C-style union.

In application code (CLIs, web backends, SaaS apps), you will almost never write unsafe. When low-level code does need it, the Rust rule is to wrap the unsafe block inside a tiny safe function that enforces every invariant up front and documents why it is sound with a // SAFETY: comment.

Here is our verified split_two_mut helper from fundamentals/src/concurrency_and_macros.rs (the same technique the standard library uses for slice::split_at_mut):

pub fn split_two_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
    let len = slice.len();
    assert!(mid <= len, "mid out of bounds");
    let ptr = slice.as_mut_ptr();

    // SAFETY: `mid <= len`, so both regions lie inside `slice` and do not overlap.
    unsafe {
        (
            std::slice::from_raw_parts_mut(ptr, mid),
            std::slice::from_raw_parts_mut(ptr.add(mid), len - mid),
        )
    }
}

The caller gets a 100% safe function returning two disjoint mutable slices, and if a memory bug ever appears, you know immediately to audit only the tiny unsafe blocks in your codebase.

Async Rust and Tokio

OS threads work great when you have a dozen CPU-heavy tasks. They stop scaling cleanly when a web server needs to hold 20,000 open HTTP connections, database queries, or WebSockets at the same time, because each OS thread reserves megabytes of stack memory and costs kernel context switches.

That is where async Rust comes in.

Why async exists alongside OS threads

Think of the difference simply:

  • Threads are for parallel CPU work (image resizing, compression, number crunching across CPU cores).
  • Async tasks are for concurrent I/O work (waiting on sockets, HTTP requests, timers, and database queries without tying up a thread while waiting).

Futures are lazy until polled

When you write async fn fetch_page(), the compiler rewrites your function into a compact state machine that implements the Future trait.

Unlike JavaScript Promises (which begin executing the moment you construct them), Rust futures are completely lazy. Calling fetch_page() does zero work until you .await it or pass it to an executor. That design also makes cancellation clean: dropping a future stops it right at its last .await point without extra cancellation tokens.

Inside the Tokio multi-threaded runtime

Rust intentionally keeps the async runtime out of the standard library so embedded firmware and kernels stay tiny. For servers and networked CLIs, Tokio is the standard runtime.

Click through the interactive diagram below to see how Tokio multiplexes thousands of lightweight tasks onto a small pool of worker threads:

Fig 3 · 1/3How Tokio multiplexes async tasks across worker threads
Step 1 · Thousands of tiny tasks share a few OS threads

Annotate async fn main() with #[tokio::main] to start the runtime with one worker thread per CPU core. For single-threaded CLI tools or tests, you can also run #[tokio::main(flavor = "current_thread")].

Spawning concurrent tasks with JoinSet

If you .await two network calls one after the other (a().await; b().await;), they run sequentially. To run them concurrently, either use tokio::join!(a(), b()) for a fixed pair of futures, or spawn dynamic batches onto a tokio::task::JoinSet:

use tokio::task::JoinSet;

let mut tasks = JoinSet::new();
for id in 1..=4 {
    tasks.spawn(async move { id * 10 });
}

let mut results = Vec::new();
while let Some(joined) = tasks.join_next().await {
    results.push(joined.expect("task panicked"));
}

A huge advantage of JoinSet over raw tokio::spawn handles is structured cleanup: if the JoinSet is dropped early (for example because an error returned via ?), Tokio automatically aborts all remaining background tasks in the set so they never leak.

Async channels: mpsc, oneshot, and broadcast

Tokio ships async-aware channels inside tokio::sync that yield cleanly to the runtime instead of blocking an OS thread:

ChannelPatternTypical use case
tokio::sync::mpscMany senders, one receiver (bounded)Work queues and backpressure between tasks
tokio::sync::oneshotOne sender, one receiver, single valueSending a reply back from a background actor
tokio::sync::broadcastMany senders, many receiversFan-out notifications and WebSocket chat rooms
tokio::sync::watchSingle latest valueLive config reloads and shutdown signals
// Bounded mpsc channel (provides backpressure when 8 items are queued)
let (tx, mut rx) = tokio::sync::mpsc::channel(8);
tokio::spawn(async move {
    tx.send("job-1").await.unwrap();
});
assert_eq!(rx.recv().await, Some("job-1"));

// Oneshot channel for a single reply
let (otx, orx) = tokio::sync::oneshot::channel();
otx.send(42).unwrap();
assert_eq!(orx.await.unwrap(), 42);

Always prefer bounded mpsc::channel(capacity) over unbounded_channel() in servers so a slow consumer applies natural backpressure instead of growing memory until the process crashes with OOM.

Timeouts, intervals, and tokio::select!

Always bound network calls with a deadline by wrapping any future in tokio::time::timeout:

use std::time::Duration;

let result = tokio::time::timeout(
    Duration::from_millis(200),
    async { "done" },
)
.await;

When you need to race multiple async events (like waiting for either Ctrl+C OR a Unix SIGTERM signal, or polling a channel alongside a periodic tokio::time::interval), use tokio::select!:

tokio::select! {
    _ = ctrl_c => {},
    _ = terminate => {},
}

One important detail to know about tokio::select!: as soon as one branch finishes, Tokio drops (cancels) all the other pending branches. Standard operations like rx.recv(), TcpListener::accept(), and tokio::time::sleep() are cancellation-safe, whereas partially reading into a fresh local buffer inside a select! branch can lose bytes if another branch wins first.

The golden rule: never block a Tokio worker (and Mutex across .await)

Keep two rules top of mind in every async Rust service:

  1. Never run blocking code directly on a Tokio worker thread. Calling std::thread::sleep, synchronous file I/O, or CPU-heavy password hashing inside an async fn freezes that worker thread and stalls every other task queued on it. Offload blocking work onto Tokio’s dedicated blocking pool with spawn_blocking:
let total = tokio::task::spawn_blocking(|| {
    (1u64..=100).sum::<u64>()
})
.await
.unwrap();
  1. Never hold a std::sync::MutexGuard across an .await point. Not only can it deadlock the runtime, rustc will reject the future as not Send inside tokio::spawn. Either lock, read/mutate in a short synchronous { ... } scope, drop the guard, and THEN .await, or use tokio::sync::Mutex only when you genuinely must hold a lock across an async I/O call.

Project 1: building urlprobe, an async CLI

Let’s put everything we covered into a real, useful command-line tool.

We will build urlprobe, a standalone async CLI that checks a list of URLs concurrently, caps in-flight requests with a Semaphore, enforces per-request timeouts, and outputs either a clean status table or formatted JSON.

Designing the CLI and dependencies

We combine 6 battle-tested crates in urlprobe/Cargo.toml: clap (derive-based flags and --help), reqwest (async HTTP client using pure-Rust rustls so there is no OpenSSL system dependency), tokio (async runtime), serde + serde_json (JSON output), and thiserror (typed errors):

[package]
name = "urlprobe"
version.workspace = true
edition.workspace = true

[dependencies]
clap = { version = "4.6", features = ["derive"] }
reqwest = { version = "0.13", default-features = false, features = ["rustls", "http2"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "2.0"
tokio = { version = "1.54", features = ["macros", "rt-multi-thread", "sync", "time"] }

Deriving flags and help text with clap

With clap’s Parser derive macro, a plain Rust struct becomes a complete CLI with short/long flags, defaults, type validation, --version, and --help pulled straight from your doc comments:

use std::sync::Arc;
use std::time::{Duration, Instant};

use clap::Parser;
use serde::Serialize;
use thiserror::Error;
use tokio::sync::Semaphore;
use tokio::task::JoinSet;

/// Check multiple HTTP endpoints concurrently and report status + latency.
#[derive(Debug, Parser)]
#[command(name = "urlprobe", version, about)]
struct Cli {
    /// One or more URLs to check
    #[arg(required = true)]
    urls: Vec<String>,

    /// Maximum number of concurrent requests
    #[arg(short = 'c', long, default_value_t = 4)]
    concurrency: usize,

    /// Per-request timeout in seconds
    #[arg(short = 't', long, default_value_t = 5)]
    timeout_secs: u64,

    /// Print results as formatted JSON
    #[arg(long)]
    json: bool,
}

Typed errors with thiserror

Next, we define our structured error enum and serializable result struct:

#[derive(Debug, Error)]
enum ProbeError {
    #[error("failed to build HTTP client: {0}")]
    Client(#[from] reqwest::Error),

    #[error("concurrency must be at least 1")]
    InvalidConcurrency,
}

#[derive(Debug, Serialize)]
struct ProbeResult {
    url: String,
    status: Option<u16>,
    ok: bool,
    latency_ms: u128,
    error: Option<String>,
}

Bounded concurrency with Semaphore and JoinSet

Now we write check_one to measure a single URL, and run to fan out across all URLs while never exceeding cli.concurrency active HTTP requests at once:

async fn check_one(client: reqwest::Client, url: String) -> ProbeResult {
    let started = Instant::now();
    match client.get(&url).send().await {
        Ok(resp) => {
            let code = resp.status().as_u16();
            ProbeResult {
                url,
                status: Some(code),
                ok: (200..400).contains(&code),
                latency_ms: started.elapsed().as_millis(),
                error: None,
            }
        }
        Err(err) => ProbeResult {
            url,
            status: None,
            ok: false,
            latency_ms: started.elapsed().as_millis(),
            error: Some(err.to_string()),
        },
    }
}

async fn run(cli: Cli) -> Result<Vec<ProbeResult>, ProbeError> {
    if cli.concurrency == 0 {
        return Err(ProbeError::InvalidConcurrency);
    }

    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(cli.timeout_secs))
        .user_agent("urlprobe/0.1")
        .build()?;

    let limit = Arc::new(Semaphore::new(cli.concurrency));
    let mut tasks = JoinSet::new();

    for url in cli.urls {
        let client = client.clone();
        let permit = Arc::clone(&limit);
        tasks.spawn(async move {
            let _guard = permit.acquire_owned().await.expect("semaphore open");
            check_one(client, url).await
        });
    }

    let mut results = Vec::new();
    while let Some(joined) = tasks.join_next().await {
        if let Ok(result) = joined {
            results.push(result);
        }
    }

    results.sort_by(|a, b| a.url.cmp(&b.url));
    Ok(results)
}

Look closely at two important Rust idioms inside run:

  1. reqwest::Client wraps an internal Arc, so client.clone() is cheap and shares one connection and TLS session pool across every spawned task.
  2. We bind let _guard = permit.acquire_owned().await... (never let _ = ...). Binding to _guard keeps the permit alive until check_one completes, then drops it automatically via Drop so the next waiting task proceeds. Writing let _ = ... would drop the permit immediately on that line and break the concurrency cap!

Wiring main, JSON output, and exit codes

main prints either pretty JSON (for piping into jq) or an aligned status table, and exits with status 1 if any URL failed or 2 on invalid configuration so urlprobe works natively inside CI scripts:

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    let as_json = cli.json;

    match run(cli).await {
        Ok(results) => {
            if as_json {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&results).expect("serialize")
                );
            } else {
                for r in &results {
                    match (r.status, &r.error) {
                        (Some(code), _) => {
                            let label = if r.ok { "OK  " } else { "WARN" };
                            println!(
                                "{label} {code}  {:>4}ms  {}",
                                r.latency_ms, r.url
                            );
                        }
                        (None, Some(err)) => {
                            println!(
                                "ERR  ---  {:>4}ms  {} ({err})",
                                r.latency_ms, r.url
                            );
                        }
                        _ => {}
                    }
                }
            }

            if results.iter().any(|r| !r.ok) {
                std::process::exit(1);
            }
        }
        Err(err) => {
            eprintln!("error: {err}");
            std::process::exit(2);
        }
    }
}

Testing CLI parsing and running the compiled binary

Because Cli derives Parser and run returns a typed Result, testing both flag parsing and error handling takes 20 lines and runs in 0.00s without making a single real network call:

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_cli_flags() {
        let cli = Cli::parse_from([
            "urlprobe",
            "-c",
            "8",
            "--json",
            "https://flaviocopes.com",
        ]);
        assert_eq!(cli.concurrency, 8);
        assert!(cli.json);
        assert_eq!(cli.urls, vec!["https://flaviocopes.com"]);
    }

    #[tokio::test]
    async fn rejects_zero_concurrency() {
        let cli = Cli {
            urls: vec!["https://flaviocopes.com".into()],
            concurrency: 0,
            timeout_secs: 5,
            json: false,
        };
        let err = run(cli).await.expect_err("zero concurrency should fail");
        assert!(matches!(err, ProbeError::InvalidConcurrency));
    }
}

After compiling with cargo build -p urlprobe --release, I ran the 7.1 MB standalone binary against four live endpoints:

Terminal output running compiled urlprobe binary against 4 live URLs and showing 7.1M binary size

All four requests ran concurrently, finishing in the time of the slowest site (811ms for rust-lang.org, while flaviocopes.com answered in 387ms), with zero runtime dependencies.

Project 2: building pulseapi with Axum and SQLite

Now let’s build a production-shaped HTTP backend using Axum (the web framework from the Tokio team), SQLx (async SQLite), Tower HTTP middleware, structured tracing logs, and graceful shutdown.

We will build pulseapi, a small JSON API that records and queries service uptime pings:

  • GET /health returns { "status": "ok" }
  • POST /pings validates and inserts a service ping into SQLite, returning 201 Created
  • GET /pings returns the latest 50 pings
  • GET /pings/{service} returns the most recent ping for one service, or 404 Not Found

Architecture and dependencies

We keep the router, handlers, error mapping, and tests inside pulseapi/src/lib.rs, and put only server boot and shutdown wiring in pulseapi/src/main.rs. Here is pulseapi/Cargo.toml:

[package]
name = "pulseapi"
version.workspace = true
edition.workspace = true

[dependencies]
axum = "0.8"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.9", default-features = false, features = ["runtime-tokio", "sqlite", "macros"] }
thiserror = "2.0"
tokio = { version = "1.54", features = ["macros", "rt-multi-thread", "signal", "time"] }
tower-http = { version = "0.6", features = ["trace", "timeout", "cors"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"

Shared AppState and SQLite connection pools

Every Axum handler receives shared application state via State<AppState>. Because sqlx::SqlitePool wraps an internal Arc, deriving Clone on AppState lets Axum clone it cheaply for every incoming request:

use std::time::Duration;

use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use thiserror::Error;
use tower_http::cors::CorsLayer;
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;

#[derive(Clone)]
pub struct AppState {
    pub db: SqlitePool,
}

#[derive(Debug, Serialize, FromRow)]
pub struct Ping {
    pub id: i64,
    pub service: String,
    pub latency_ms: i64,
    pub ok: bool,
}

#[derive(Debug, Deserialize)]
pub struct CreatePing {
    pub service: String,
    pub latency_ms: i64,
    pub ok: bool,
}

Notice #[derive(FromRow)] on Ping: SQLx maps SQLite columns straight onto struct fields without an ORM layer.

Mapping typed errors with IntoResponse

One of the cleanest patterns in Axum is defining a single ApiError enum that implements IntoResponse. Every handler can return Result<Json<T>, ApiError> and use ? freely, while keeping internal database errors out of HTTP responses:

#[derive(Debug, Error)]
pub enum ApiError {
    #[error("validation error: {0}")]
    Validation(String),

    #[error("service not found: {0}")]
    NotFound(String),

    #[error("database error: {0}")]
    Database(#[from] sqlx::Error),
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ApiError::Validation(msg) => (StatusCode::UNPROCESSABLE_ENTITY, msg),
            ApiError::NotFound(msg) => (StatusCode::NOT_FOUND, msg),
            ApiError::Database(err) => {
                tracing::error!(error = %err, "database query failed");
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "internal server error".to_string(),
                )
            }
        };

        (status, Json(serde_json::json!({ "error": message }))).into_response()
    }
}

Routes, extractors, and parameterized SQLx queries

Axum handlers are regular async functions whose parameters are extractors (State<AppState>, Path<String>, Json<CreatePing>). Axum deserializes and validates them before your handler runs:

pub async fn init_db(url: &str) -> Result<SqlitePool, sqlx::Error> {
    let pool = SqlitePool::connect(url).await?;
    sqlx::query(
        "CREATE TABLE IF NOT EXISTS pings (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            service TEXT NOT NULL,
            latency_ms INTEGER NOT NULL,
            ok BOOLEAN NOT NULL
        )",
    )
    .execute(&pool)
    .await?;
    Ok(pool)
}

async fn health() -> Json<serde_json::Value> {
    Json(serde_json::json!({ "status": "ok" }))
}

async fn create_ping(
    State(state): State<AppState>,
    Json(payload): Json<CreatePing>,
) -> Result<(StatusCode, Json<Ping>), ApiError> {
    let service = payload.service.trim();
    if service.is_empty() {
        return Err(ApiError::Validation("service name cannot be empty".into()));
    }
    if payload.latency_ms < 0 {
        return Err(ApiError::Validation("latency_ms must be >= 0".into()));
    }

    let ping = sqlx::query_as::<_, Ping>(
        "INSERT INTO pings (service, latency_ms, ok)
         VALUES (?1, ?2, ?3)
         RETURNING id, service, latency_ms, ok",
    )
    .bind(service)
    .bind(payload.latency_ms)
    .bind(payload.ok)
    .fetch_one(&state.db)
    .await?;

    Ok((StatusCode::CREATED, Json(ping)))
}

async fn list_pings(
    State(state): State<AppState>,
) -> Result<Json<Vec<Ping>>, ApiError> {
    let rows = sqlx::query_as::<_, Ping>(
        "SELECT id, service, latency_ms, ok
         FROM pings
         ORDER BY id DESC
         LIMIT 50",
    )
    .fetch_all(&state.db)
    .await?;

    Ok(Json(rows))
}

async fn latest_for_service(
    State(state): State<AppState>,
    Path(service): Path<String>,
) -> Result<Json<Ping>, ApiError> {
    let row = sqlx::query_as::<_, Ping>(
        "SELECT id, service, latency_ms, ok
         FROM pings
         WHERE service = ?1
         ORDER BY id DESC
         LIMIT 1",
    )
    .bind(&service)
    .fetch_optional(&state.db)
    .await?
    .ok_or_else(|| ApiError::NotFound(service))?;

    Ok(Json(row))
}

Every SQL query uses bound placeholders (?1, ?2, ?3) so SQL injection is impossible, and .fetch_optional(...).await?.ok_or_else(...) turns a missing row into a clean 404 in one expression.

Production middleware with tower-http

Axum does not invent its own middleware system. It sits directly on Tower, so you plug in battle-tested middleware layers from tower-http with .layer(...):

pub fn router(state: AppState) -> Router {
    Router::new()
        .route("/health", get(health))
        .route("/pings", get(list_pings).post(create_ping))
        .route("/pings/{service}", get(latest_for_service))
        .layer(TraceLayer::new_for_http())
        .layer(TimeoutLayer::with_status_code(
            StatusCode::REQUEST_TIMEOUT,
            Duration::from_secs(10),
        ))
        .layer(CorsLayer::permissive())
        .with_state(state)
}

Those three lines give pulseapi structured request/response spans, a hard 10-second per-request timeout returning 408 Request Timeout, and CORS headers (tighten CorsLayer to your real origins before shipping a browser-facing production API).

Structured logging and graceful SIGTERM shutdown

In production, a deploy or systemctl restart should drain active requests instead of cutting sockets mid-response. axum::serve(...).with_graceful_shutdown(...) pairs cleanly with tokio::select! in pulseapi/src/main.rs:

use std::net::SocketAddr;

use tokio::net::TcpListener;
use tracing_subscriber::EnvFilter;

use pulseapi::{AppState, init_db, router};

async fn shutdown_signal() {
    let ctrl_c = async {
        tokio::signal::ctrl_c()
            .await
            .expect("install Ctrl+C handler");
    };

    #[cfg(unix)]
    let terminate = async {
        tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
            .expect("install SIGTERM handler")
            .recv()
            .await;
    };

    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_env_filter(
            EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()),
        )
        .init();

    let db_url = std::env::var("DATABASE_URL")
        .unwrap_or_else(|_| "sqlite::memory:".into());
    let port: u16 = std::env::var("PORT")
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(3000);

    let db = init_db(&db_url).await.expect("initialize database");
    let app = router(AppState { db });

    let addr = SocketAddr::from(([127, 0, 0, 1], port));
    let listener = TcpListener::bind(addr).await.expect("bind listener");
    tracing::info!(%addr, "pulseapi listening");

    axum::serve(listener, app)
        .with_graceful_shutdown(shutdown_signal())
        .await
        .expect("serve pulseapi");
}

Run it with RUST_LOG=info,tower_http=debug to inspect every request and response duration.

Zero-port testing with tower::ServiceExt::oneshot

Because router(state) lives in src/lib.rs, we can dispatch synthetic HTTP requests straight through our Axum routes, Tower middleware, JSON parser, and in-memory SQLite database without binding a network port:

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::Request;
    use http_body_util::BodyExt;
    use tower::ServiceExt;

    async fn test_app() -> Router {
        let db = init_db("sqlite::memory:").await.expect("in-memory sqlite");
        router(AppState { db })
    }

    #[tokio::test]
    async fn creates_and_fetches_service_ping() {
        let app = test_app().await;

        let create_req = Request::builder()
            .method("POST")
            .uri("/pings")
            .header("content-type", "application/json")
            .body(Body::from(
                r#"{"service":"flaviocopes.com","latency_ms":42,"ok":true}"#,
            ))
            .unwrap();

        let resp = app.clone().oneshot(create_req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::CREATED);

        let get_req = Request::builder()
            .uri("/pings/flaviocopes.com")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(get_req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let bytes = resp.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(body["service"], "flaviocopes.com");
        assert_eq!(body["latency_ms"], 42);
        assert_eq!(body["ok"], true);
    }

    #[tokio::test]
    async fn rejects_empty_service_name_with_422() {
        let app = test_app().await;

        let req = Request::builder()
            .method("POST")
            .uri("/pings")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"service":"  ","latency_ms":10,"ok":true}"#))
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[tokio::test]
    async fn returns_404_for_unknown_service() {
        let app = test_app().await;

        let req = Request::builder()
            .uri("/pings/missing")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }
}

Running cargo test -p pulseapi --lib executes all 3 integration tests in 0.00s against fresh isolated SQLite instances:

Terminal output running cargo test on pulseapi with all 3 Axum and SQLite tests passing in 0.00s

Live latency, RAM usage, and when to reach for Laravel Rust

When I compiled pulseapi in release mode (6.3 MB standalone binary with Axum, Tokio, Tower HTTP, and SQLite embedded) and sent real requests with curl:

  • POST /pings inserted a row and returned JSON in 0.92 ms.
  • GET /pings/flaviocopes.com queried SQLite and returned JSON in 0.69 ms.
  • The live running server used 6.2 MB of RAM (RSS).

Building directly on Axum + Tokio + SQLx is ideal for lean JSON APIs, webhook receivers, and internal microservices where you want full control and a tiny 6 MB binary. When you want a full-stack web application with session auth, database migrations, queues, durable workflows, WebSockets, and Inertia + React already wired together on top of this exact Axum + Tokio + SQLx foundation, read my complete guide to Laravel Rust.

Release builds, cross-compilation, and deployment

Debug builds (cargo build) disable LLVM optimizations and include full debug symbols so your edit-compile loop stays snappy. Never benchmark or deploy a debug binary!

Optimizing Cargo release profiles (LTO and strip)

Build optimized binaries with:

cargo build --workspace --release

If you want smaller container images or downloadable CLI binaries, add a [profile.release] section to your root Cargo.toml:

[profile.release]
lto = "thin"
codegen-units = 1
strip = true

lto = "thin" lets LLVM optimize across crate boundaries without massive compile times, and strip = true strips debug symbols from the final executable.

Workspace measurements from real builds

Here are all the real measurements from our Rust 1.100.1 workspace on Apple Silicon:

ArtifactScopeTestsRelease binaryMeasured runtime
fundamentals6 core modules + doc tests17 passed (0.00s)Library crate0 Clippy warnings (-D warnings)
urlprobeAsync CLI (clap + reqwest + tokio)2 passed (0.00s)7.1 MB4 live URLs in 811 ms parallel
pulseapiWeb API (axum + tower-http + sqlx)3 passed (0.00s)6.3 MB6.2 MB RSS, 0.69 ms GET, 0.92 ms POST

Cross-compiling for Linux servers

If you develop on macOS and deploy to Linux (x86_64 or aarch64), you have three reliable options:

  1. Build in Docker or CI matching your target Linux distro (simplest when crates link native C code like SQLite).
  2. Use cargo-zigbuild (cargo zigbuild --release --target x86_64-unknown-linux-gnu) to cross-compile straight from macOS with Zig acting as the C linker.
  3. Add static musl targets with rustup target add x86_64-unknown-linux-musl when you want a completely static Linux executable with zero glibc version mismatch across distros.

Deploying with systemd, Docker, or a PaaS

Once you have the single compiled binary, shipping it is refreshingly boring:

  • On a Linux VPS: Copy the binary to /usr/local/bin/pulseapi, put it behind Caddy or Nginx for TLS, and run it under a systemd unit that sends SIGTERM on restart (my Linux Server Handbook covers the full systemd and reverse proxy setup).
  • In Docker: Compile in a rust:1 builder stage and copy just the single binary into debian:bookworm-slim or gcr.io/distroless/cc for an image under 30 MB (see the multi-stage patterns in my Docker Handbook).
  • On a PaaS: Railway, Fly.io, and Laravel Cloud (which supports both raw Axum services and Laravel Rust apps) detect Cargo.toml and build the release binary for you.

How I would use Rust

Rust is not the right tool for every job, and picking it out of hype wastes time.

Here is the decision framework I use when deciding whether to reach for Rust or another stack:

When to choose Rust vs Go, TypeScript, or LaravelDecision guide for choosing Rust for CLIs, high-throughput services, and systems tools versus Astro, Go, or Laravel.YesNoYesNoYesNoStarting a newprojectContent site, UIprototype, or quickglue script?Use Astro,TypeScript, orPythonCLI tool, systemsutility, orhigh-throughput API?Use Rust with clapor AxumFull-stack SaaS webapp?Use Laravel Rust orLaravel PHPRust or Go both workgreat

Where Rust pays off immediately

  • Developer CLIs and local utilities. A tool like urlprobe compiles to one 7 MB executable with zero runtime dependencies, starts instantly, and distributes cleanly over Homebrew or GitHub Releases.
  • High-throughput APIs, webhook processors, and background workers. An Axum + Tokio + SQLite service using 6 MB of RAM and answering in under a millisecond lets one tiny VPS handle workloads that would otherwise need a cluster.
  • Native desktop companions and Linux apps. When I port Mac utilities to native Linux apps using Rust and GTK4, the compiler catches threading and memory mistakes before I ever test inside a container.
  • Codebases built alongside AI coding agents. Rust’s strict type system, exhaustive match, Result error paths, and cargo clippy -- -D warnings act as an automated reviewer that blocks entire categories of agent bugs before runtime.

Where I would pick another stack

  • Static content sites and marketing pages. For flaviocopes.com, Astro stays simpler and builds in seconds.
  • Throwaway data-munging scripts. If I need a 30-line one-off script to reshape a CSV file, Python or Node finishes before Cargo finishes resolving crates.
  • Early throwaway UI prototypes. When requirements shift every hour and you just need to test an idea with users today, designing lifetimes and error enums adds friction you don’t need yet.

How to learn Rust without stalling

The biggest mistake developers make with Rust is reading 400 pages of lifetime theory before compiling a real program.

Install rustup, run cargo new, and build a small CLI that solves a real annoyance on your machine. Clone values freely in week one while you get comfortable with structs, enums, Result, and iterators, and let rustc and cargo clippy teach you ownership one compiler message at a time.

Want me to talk about your product? You can sponsor this site.

Related posts about rust: