Skip to content

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 Send and Sync make data races a compile-time error, and what unsafe code 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.

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.

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.

  • Exhaustive pattern matching on enums.
  • Iterator chains (map, filter, collect) instead of explicit loops.
  • impl Trait for return-position polymorphism.
  • The newtype pattern for type safety, such as struct Miles(f64).
  • The builder pattern for complex construction.
  • From and Into conversions instead of explicit casts.
  • derive macros for common trait implementations.

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.

#ExerciseConceptsDifficulty (1-5)Worked elsewhere
01Vec<T> from scratchUnsafe, RawVec, Drop, Deref3Do this before the Candle model runner
02Doubly linked listRc<RefCell<T>> or unsafe, borrow checker challenges4A radix tree over token ids
03Hash map (Robin Hood)Hashing, Entry API, generics with trait bounds4A Robin Hood hash map
04Channel (mpsc clone)Arc<Mutex<T>>, Condvar, Send bounds4Async Rust and tokio
05Iterator adaptor libraryIterator trait, associated types, lazy evaluation3Fast BPE in Rust
06CLI argument parserLifetimes, &str vs String, builder pattern2
07Async TCP echo serverasync/await, tokio, Pin, Future4Async Rust and tokio; the OpenAI-compatible server on tokio
08ECS (Entity Component System)Trait objects vs enums, Any, downcast, arena allocation5
09Proc macro for derive(Builder)Procedural macros, syn, quote, token streams4
10Lock-free stackAtomicPtr, compare_exchange, ABA problem5
  • 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 Send type may be moved to another thread and a Sync type may be shared between threads by reference, so the compiler rejects code that could race.
  • Unsafe Rust: code inside an unsafe block 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 enum with payloads; with exhaustive matching, every case must be handled explicitly.
  • Exhaustive pattern matching: a match that 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.