Module 20 Exercises — Idioms, Performance & Capstones
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be clear that this page is different: it is four projects, not a set of drills. Read the spec, build the smallest version that runs end to end, and only then add features.
For each capstone, plan to finish with these three things — they are what turn a project into something you can show:
- a
READMEexplaining what it does and how to run it; - tests for the parts that actually contain logic;
cargo clippy -- -D warningsandcargo fmt --checkboth passing.
Start with minigrep. It touches modules 3, 5, 8, 9, 10 and 16, and it is small enough to finish in one sitting — which matters more than scope for the first one.
Capstone Projects
Each project has a spec, a suggested architecture, and stretch goals. Build them in order; each exercises more of the course than the last.
Capstone 1 — minigrep: a command-line search tool
Modules exercised: 3, 5, 8, 9, 10, 16
Spec
minigrep <pattern> <file> # print matching lines
minigrep -i <pattern> <file> # case-insensitive
minigrep -n <pattern> <file> # show line numbers
minigrep -c <pattern> <file> # count only
minigrep <pattern> <file1> <file2> # multiple files, prefix with filenameArchitecture
src/
├── main.rs # arg parsing, error reporting, exit codes
└── lib.rs # Config::build, run, search, search_case_insensitive
Starter
// src/lib.rs
use std::error::Error;
use std::fs;
pub struct Config {
pub pattern: String,
pub files: Vec<String>,
pub ignore_case: bool,
pub line_numbers: bool,
pub count_only: bool,
}
impl Config {
pub fn build(args: &[String]) -> Result<Config, String> {
let mut pattern = None;
let mut files = Vec::new();
let (mut ignore_case, mut line_numbers, mut count_only) = (false, false, false);
for arg in &args[1..] {
match arg.as_str() {
"-i" => ignore_case = true,
"-n" => line_numbers = true,
"-c" => count_only = true,
other if other.starts_with('-') => return Err(format!("unknown flag {other}")),
other if pattern.is_none() => pattern = Some(other.to_string()),
other => files.push(other.to_string()),
}
}
let pattern = pattern.ok_or("usage: minigrep [-inc] <pattern> <file>...")?;
if files.is_empty() { return Err("no input files".to_string()); }
Ok(Config { pattern, files, ignore_case, line_numbers, count_only })
}
}
pub fn search<'a>(pattern: &str, contents: &'a str, ignore_case: bool) -> Vec<(usize, &'a str)> {
let needle = if ignore_case { pattern.to_lowercase() } else { pattern.to_string() };
contents
.lines()
.enumerate()
.filter(|(_, line)| {
if ignore_case { line.to_lowercase().contains(&needle) } else { line.contains(&needle) }
})
.map(|(i, line)| (i + 1, line))
.collect()
}
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
let show_filename = config.files.len() > 1;
for file in &config.files {
let contents = fs::read_to_string(file)
.map_err(|e| format!("{file}: {e}"))?;
let matches = search(&config.pattern, &contents, config.ignore_case);
if config.count_only {
println!("{}{}", if show_filename { format!("{file}:") } else { String::new() },
matches.len());
continue;
}
for (num, line) in matches {
let prefix = match (show_filename, config.line_numbers) {
(true, true) => format!("{file}:{num}:"),
(true, false) => format!("{file}:"),
(false, true) => format!("{num}:"),
(false, false) => String::new(),
};
println!("{prefix}{line}");
}
}
Ok(())
}// src/main.rs
use std::env;
use std::process;
fn main() {
let args: Vec<String> = env::args().collect();
let config = minigrep::Config::build(&args).unwrap_or_else(|err| {
eprintln!("error: {err}");
process::exit(2);
});
if let Err(e) = minigrep::run(config) {
eprintln!("error: {e}");
process::exit(1);
}
}Your tasks
- Write unit tests for
search(case-sensitive, insensitive, no matches, multiline). - Write an integration test using a temp file.
- Add
-v(invert match) and-r(recurse into directories). - Read from stdin when no file is given.
Stretch: replace hand-rolled parsing with clap; add regex support with the regex
crate; colorize matches with owo-colors.
Capstone 2 — Task manager with JSON persistence
Modules exercised: 6, 7, 8, 9, 10, 12, 16
Spec
tasks add "Write the report" --priority high --due 2026-09-01 --tag work
tasks list [--status pending] [--tag work] [--sort priority]
tasks done 3
tasks remove 3
tasks statsState persists to ~/.tasks.json between runs.
Design sketch
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Priority { Low, Medium, High, Critical }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "lowercase")]
pub enum Status {
Pending,
InProgress { started: String },
Done { completed: String },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
pub id: u32,
pub title: String,
pub priority: Priority,
pub status: Status,
pub tags: Vec<String>,
pub due: Option<String>,
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct TaskList {
next_id: u32,
tasks: Vec<Task>,
}
impl TaskList {
pub fn load(path: &Path) -> Result<Self, TaskError> { /* handle "file missing" as empty */ }
pub fn save(&self, path: &Path) -> Result<(), TaskError> { /* write atomically */ }
pub fn add(&mut self, title: impl Into<String>, priority: Priority) -> u32 { }
pub fn complete(&mut self, id: u32) -> Result<&Task, TaskError> { }
pub fn remove(&mut self, id: u32) -> Result<Task, TaskError> { }
pub fn filter(&self, f: impl Fn(&Task) -> bool) -> Vec<&Task> { }
pub fn stats(&self) -> Stats { }
}Your tasks
- Define a
TaskErrorenum withthiserror, covering IO, JSON, and "no such id". - Implement
DisplayforTaskproducing a one-line summary with priority coloring. - Sort by
(priority desc, due asc, id asc)usingsort_bywith.then_with. - Save atomically: write to
.tmp, then rename, so a crash never corrupts the file. - Test every public method, including load-from-missing-file.
Stretch: add --json output mode; add subtask nesting; add a search command doing
fuzzy matching.
Capstone 3 — Multithreaded web server
Modules exercised: 5, 8, 12, 15, 16, 17
Spec
A HTTP/1.1 server that serves static files from a directory, handles requests on a thread pool, and shuts down gracefully on Ctrl-C.
Design sketch
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
struct Request { method: String, path: String, headers: Vec<(String, String)> }
fn parse_request(stream: &mut TcpStream) -> Result<Request, ServerError> {
let mut reader = BufReader::new(stream);
let mut request_line = String::new();
reader.read_line(&mut request_line)?;
let mut parts = request_line.split_whitespace();
let method = parts.next().ok_or(ServerError::Malformed)?.to_string();
let path = parts.next().ok_or(ServerError::Malformed)?.to_string();
let mut headers = Vec::new();
loop {
let mut line = String::new();
reader.read_line(&mut line)?;
if line.trim().is_empty() { break; }
if let Some((k, v)) = line.split_once(':') {
headers.push((k.trim().to_lowercase(), v.trim().to_string()));
}
}
Ok(Request { method, path, headers })
}
fn handle(mut stream: TcpStream, root: &Path) {
let req = match parse_request(&mut stream) { Ok(r) => r, Err(_) => return };
let (status, body, content_type) = route(&req, root);
let response = format!(
"HTTP/1.1 {status}\r\nContent-Length: {}\r\nContent-Type: {content_type}\r\n\r\n",
body.len()
);
let _ = stream.write_all(response.as_bytes());
let _ = stream.write_all(&body);
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
let pool = ThreadPool::new(4); // from module 17's exercise
for stream in listener.incoming() {
let stream = stream.unwrap();
pool.execute(move || handle(stream, Path::new("./public")));
}
}Your tasks
- Reuse the
ThreadPoolfrom module 17, exercise 5. - Path traversal defense: reject any path containing
..or resolving outside the root. Canonicalize and verify the prefix. This is the security-critical part. - Serve correct
Content-Typeby extension; return 404 for missing files, 405 for non-GET methods, 400 for malformed requests. - Add a request log line with method, path, status, and duration.
- Graceful shutdown: handle Ctrl-C, stop accepting, finish in-flight requests, join workers.
- Integration tests using a real
TcpStreamclient against a server on port 0.
Stretch: keep-alive connections; gzip with flate2; a /health JSON endpoint;
rewrite the whole thing with tokio and compare throughput under load.
Capstone 4 — Concurrent web crawler (async)
Modules exercised: everything, especially 14, 17, 18
Spec
crawler https://example.com --depth 3 --concurrency 10 --output sitemap.jsonCrawl breadth-first up to a depth limit, stay on the origin domain, respect a concurrency cap, deduplicate URLs, handle failures with retries, and report statistics.
Design sketch
use std::collections::HashSet;
use std::sync::Arc;
use tokio::sync::{Mutex, Semaphore};
#[derive(Debug, Clone)]
struct Page { url: String, depth: u32, links: Vec<String>, status: u16, bytes: usize }
struct Crawler {
client: reqwest::Client,
seen: Arc<Mutex<HashSet<String>>>,
limit: Arc<Semaphore>,
origin: String,
max_depth: u32,
}
impl Crawler {
async fn crawl(&self, start: &str) -> Vec<Page> {
let mut frontier = vec![(start.to_string(), 0u32)];
let mut results = Vec::new();
while !frontier.is_empty() {
let batch: Vec<_> = frontier
.drain(..)
.map(|(url, depth)| {
let this = self.clone_handles();
tokio::spawn(async move { this.fetch_one(url, depth).await })
})
.collect();
let mut next = Vec::new();
for handle in batch {
if let Ok(Some(page)) = handle.await {
if page.depth < self.max_depth {
for link in &page.links {
next.push((link.clone(), page.depth + 1));
}
}
results.push(page);
}
}
frontier = self.dedupe(next).await;
}
results
}
}Your tasks
- Fetch with
reqwest, parse links withscraper(or a hand-written extractor forhref="..."). - Normalize URLs: resolve relative paths, strip fragments, drop non-http schemes, and filter to the origin host.
- Cap concurrency with a
Semaphore; add a per-requesttimeoutand 3 retries with exponential backoff. - Track statistics: pages crawled, total bytes, failures by status, wall-clock time, and the deepest path found.
- Serialize the sitemap to JSON with
serde_json. - Handle Ctrl-C: stop scheduling new fetches, await in-flight ones, write partial output.
Stretch: honour robots.txt; add a politeness delay per host; render the sitemap as a
Graphviz .dot file; add a progress bar with indicatif.
Where to go next
Read
- The Rust Programming Language (the Book) — free at doc.rust-lang.org/book
- Rust for Rustaceans by Jon Gjengset — the natural sequel to this course
- Rust Atomics and Locks by Mara Bos — free online, the definitive concurrency text
- The Rust API Guidelines — rust-lang.github.io/api-guidelines
Practice
- Rustlings (small compiler-driven exercises)
- Exercism's Rust track (mentored)
- Advent of Code in Rust
- Contribute to a crate you already use — start with documentation fixes
Specialize
| Domain | Crates to learn |
|---|---|
| Web backend | axum, tokio, sqlx, serde |
| CLI tools | clap, indicatif, owo-colors, anyhow |
| Systems / embedded | embassy, no_std, defmt |
| Data / ML | polars, ndarray, candle |
| Game dev | bevy, wgpu |
| WebAssembly | wasm-bindgen, leptos |
Habits worth keeping
- Run
cargo clippybefore every commit; it will keep teaching you idioms for years. - Read the standard library source. It's unusually readable and full of good patterns.
- When you fight the borrow checker for more than 20 minutes, the design is wrong. Change the design, not the annotations.
- Prefer boring code. Rust rewards clarity more than cleverness.
Final self-check
If you can answer these without looking anything up, you've absorbed the course:
- Explain ownership, borrowing, and lifetimes to someone who knows Python — in three sentences each.
- When would you choose
Box<dyn Trait>over a generic parameter? - Why can't
Rc<T>cross a thread boundary, and what do you use instead? - What does
?desugar to, and which trait makes it convert error types? - Given a slow program, what are the first three things you check?
- When is
unsafejustified, and what must you write alongside it? - Design the type for a config value that is either a literal string, an environment variable reference, or a file path — and explain why your design makes illegal states unrepresentable.
Congratulations. Go build something.
