Skip to content
RustLearn

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 README explaining what it does and how to run it;
  • tests for the parts that actually contain logic;
  • cargo clippy -- -D warnings and cargo fmt --check both 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

bash
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 filename

Architecture

src/
├── main.rs       # arg parsing, error reporting, exit codes
└── lib.rs        # Config::build, run, search, search_case_insensitive

Starter

rust
// 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(())
}
rust
// 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

  1. Write unit tests for search (case-sensitive, insensitive, no matches, multiline).
  2. Write an integration test using a temp file.
  3. Add -v (invert match) and -r (recurse into directories).
  4. 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

bash
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 stats

State persists to ~/.tasks.json between runs.

Design sketch

rust
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

  1. Define a TaskError enum with thiserror, covering IO, JSON, and "no such id".
  2. Implement Display for Task producing a one-line summary with priority coloring.
  3. Sort by (priority desc, due asc, id asc) using sort_by with .then_with.
  4. Save atomically: write to .tmp, then rename, so a crash never corrupts the file.
  5. 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

rust
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

  1. Reuse the ThreadPool from module 17, exercise 5.
  2. Path traversal defense: reject any path containing .. or resolving outside the root. Canonicalize and verify the prefix. This is the security-critical part.
  3. Serve correct Content-Type by extension; return 404 for missing files, 405 for non-GET methods, 400 for malformed requests.
  4. Add a request log line with method, path, status, and duration.
  5. Graceful shutdown: handle Ctrl-C, stop accepting, finish in-flight requests, join workers.
  6. Integration tests using a real TcpStream client 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

bash
crawler https://example.com --depth 3 --concurrency 10 --output sitemap.json

Crawl 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

rust
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

  1. Fetch with reqwest, parse links with scraper (or a hand-written extractor for href="...").
  2. Normalize URLs: resolve relative paths, strip fragments, drop non-http schemes, and filter to the origin host.
  3. Cap concurrency with a Semaphore; add a per-request timeout and 3 retries with exponential backoff.
  4. Track statistics: pages crawled, total bytes, failures by status, wall-clock time, and the deepest path found.
  5. Serialize the sitemap to JSON with serde_json.
  6. 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

DomainCrates to learn
Web backendaxum, tokio, sqlx, serde
CLI toolsclap, indicatif, owo-colors, anyhow
Systems / embeddedembassy, no_std, defmt
Data / MLpolars, ndarray, candle
Game devbevy, wgpu
WebAssemblywasm-bindgen, leptos

Habits worth keeping

  1. Run cargo clippy before every commit; it will keep teaching you idioms for years.
  2. Read the standard library source. It's unusually readable and full of good patterns.
  3. When you fight the borrow checker for more than 20 minutes, the design is wrong. Change the design, not the annotations.
  4. 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:

  1. Explain ownership, borrowing, and lifetimes to someone who knows Python — in three sentences each.
  2. When would you choose Box<dyn Trait> over a generic parameter?
  3. Why can't Rc<T> cross a thread boundary, and what do you use instead?
  4. What does ? desugar to, and which trait makes it convert error types?
  5. Given a slow program, what are the first three things you check?
  6. When is unsafe justified, and what must you write alongside it?
  7. 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.