Chapter 21: Rust
Rust gives you C’s control over memory without C’s undefined behaviour, and the price is that the compiler makes you prove your program is safe before it will build it. Ownership says who frees each value, borrowing says who may look at it and for how long, and the Send and Sync traits extend the same reasoning to threads. The exercises in this chapter are chosen because they are exactly where that proof is hard: a growable buffer with raw memory, a doubly linked list where two nodes point at each other, a channel shared between threads, a lock-free stack. Each one teaches you what the borrow checker is protecting you from, and when unsafe is the honest answer.
Concepts from other sections (2)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Data race: two accesses to the same memory from different goroutines, at least one a write, with no happens-before order between them. Read more: 6.2 Code review in Software Engineering
- Lazy evaluation: deferring computation until its result is needed. Read more: 19.5 Expression templates
The chapter is a set of exercise briefs rather than worked solutions. Several of them are the same problem a section of Algorithms, Programming and Algorithms, or AI Engineering solves in full, and for those the brief links to that section.
Learning objectives
- Describe Rust’s ownership and borrowing rules, its algebraic type system, and its
Result-based error handling.- Explain how
SendandSyncmake data races a compile-time error, and whatunsafecode must uphold by hand.- Apply core Rust idioms (exhaustive matching, iterator chains, newtypes,
From/Into) when designing a small library.- Reason through the design of each exercise before reading the matching worked solution elsewhere in the books.
Before you begin
Section titled “Before you begin”You should have written some Rust and fought the borrow checker at least once. If not, read Rust: ownership, traits, Result, cargo workspaces, std TCP in Programming and Algorithms first. The async briefs build on Async Rust and tokio: futures, tasks, channels, cancellation, hyper.
The language in brief
Section titled “The language in brief”Rust has no garbage collector. Every value has exactly one owner, and it is dropped when the owner goes out of scope. You may lend it out as any number of shared references (&T) or exactly one mutable reference (&mut T), and the compiler checks lifetimes so that no reference outlives what it points at.
The type system is strong and static, with algebraic data types (enum with payloads), traits for shared behaviour, and generics constrained by trait bounds. There is no null; absence is Option<T>. Errors are values too: Result<T, E> with the ? operator to propagate them, and no exceptions.
Concurrency is “fearless” in the sense that the compiler rejects data races: a type can cross threads only if it is Send, and be shared between them only if it is Sync. Asynchronous code uses async/await over futures, usually on the Tokio runtime. Builds use cargo and crates.io, and the edition system lets the language evolve without breaking old code. The exercises target stable Rust, edition 2021.
Idioms to practise
Section titled “Idioms to practise”- Exhaustive pattern matching on enums.
- Iterator chains (
map,filter,collect) instead of explicit loops. impl Traitfor return-position polymorphism.- The newtype pattern for type safety, such as
struct Miles(f64). - The builder pattern for complex construction.
FromandIntoconversions instead of explicit casts.derivemacros for common trait implementations.
In this chapter
Section titled “In this chapter”The briefs are listed below, ordered by concept rather than by difficulty, so choose by the difficulty rating (1 is easiest, 5 hardest) rather than by number. Worked Rust solutions for these exercises have not been written yet; where a full solution of the same problem, or one that builds directly on it, exists elsewhere in the books, the last column links to it.
| # | Exercise | Concepts | Difficulty (1-5) | Worked elsewhere |
|---|---|---|---|---|
| 01 | Vec<T> from scratch | Unsafe, RawVec, Drop, Deref | 3 | Do this before the Candle model runner |
| 02 | Doubly linked list | Rc<RefCell<T>> or unsafe, borrow checker challenges | 4 | A radix tree over token ids |
| 03 | Hash map (Robin Hood) | Hashing, Entry API, generics with trait bounds | 4 | A Robin Hood hash map |
| 04 | Channel (mpsc clone) | Arc<Mutex<T>>, Condvar, Send bounds | 4 | Async Rust and tokio |
| 05 | Iterator adaptor library | Iterator trait, associated types, lazy evaluation | 3 | Fast BPE in Rust |
| 06 | CLI argument parser | Lifetimes, &str vs String, builder pattern | 2 | |
| 07 | Async TCP echo server | async/await, tokio, Pin, Future | 4 | Async Rust and tokio; the OpenAI-compatible server on tokio |
| 08 | ECS (Entity Component System) | Trait objects vs enums, Any, downcast, arena allocation | 5 | |
| 09 | Proc macro for derive(Builder) | Procedural macros, syn, quote, token streams | 4 | |
| 10 | Lock-free stack | AtomicPtr, compare_exchange, ABA problem | 5 |
Key terms
Section titled “Key terms”- Borrow checker: the part of the Rust compiler that enforces ownership and borrowing: any number of shared references (
&T) or exactly one mutable reference (&mut T), and no reference outliving the value it points at; it rejects use-after-free and data races at compile time. - Send and Sync: Rust’s marker traits for thread safety: a
Sendtype may be moved to another thread and aSynctype may be shared between threads by reference, so the compiler rejects code that could race. - Unsafe Rust: code inside an
unsafeblock or function, where the compiler permits raw-pointer dereferences and other operations it cannot check, and the programmer must uphold the safety rules by hand. - Algebraic data type (ADT): a type built from sums (“one of these variants”) and products (“all of these fields”), such as a Rust
enumwith payloads; with exhaustive matching, every case must be handled explicitly. - Exhaustive pattern matching: a
matchthat the compiler checks covers every variant of a type, so adding a variant turns each place that does not handle it into a compile error. - Option type: a type that holds either a value or nothing, such as Rust’s
Option<T>, used instead of null so the compiler forces every use to handle absence. - Newtype pattern: wrapping an existing type in a single-field struct, such as
struct Miles(f64), so the compiler tells apart values with the same representation but different meanings, at no run-time cost.
Further reading
Section titled “Further reading”- The Rust Programming Language: free, the official book.
- Rust by Example: free, learn by doing.
- Standard library documentation: the API reference.
- The Rustonomicon: the deep dive into unsafe Rust, essential for exercises 01, 02, and 10.
- Programming Rust by Blandy, Orendorff, and Tindall: the comprehensive reference.