Skip to content
RustLearn

Module 07 Exercises — Enums & Pattern Matching

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, make sure you can:

  • write an enum whose variants carry different shapes of data;
  • destructure each of those shapes in a match;
  • explain why exhaustiveness is a feature rather than an inconvenience.

When a drill asks you to model something, resist adding a bool. Ask instead: what are the actual states this thing can be in? — and write those as variants. That habit is the whole module.

Part A — Warm-Up Drills

Short reps on the mechanics. Do them until the syntax stops costing you any thought.

🟢 Exercise 7.1 — Traffic light

Define enum Light { Red, Yellow, Green } with a method duration(&self) -> u32 (30/5/25 seconds) and next(self) -> Light. Print a 6-step cycle.

Solution
rust
#[derive(Debug, Clone, Copy)]
enum Light { Red, Yellow, Green }

impl Light {
    fn duration(&self) -> u32 {
        match self { Light::Red => 30, Light::Yellow => 5, Light::Green => 25 }
    }
    fn next(self) -> Light {
        match self { Light::Red => Light::Green, Light::Green => Light::Yellow, Light::Yellow => Light::Red }
    }
}

fn main() {
    let mut l = Light::Red;
    for _ in 0..6 {
        println!("{l:?} for {}s", l.duration());
        l = l.next();
    }
}

🟢 Exercise 7.2 — Rewrite as if let / let else

Rewrite each match with the most concise appropriate form:

rust
match maybe_name { Some(n) => println!("{n}"), None => {} }

let value = match input.parse::<i32>() { Ok(v) => v, Err(_) => return };
Solution
rust
if let Some(n) = maybe_name { println!("{n}"); }

let Ok(value) = input.parse::<i32>() else { return };

Part B — Core Exercises

The real practice. Attempt each one fully — compiler errors included — before opening a solution.

🟡 Exercise 7.3 — Shape area and exhaustiveness

Implement enum Shape with Circle, Rectangle, Triangle, and area(). Then add a Square(f64) variant without updating area and record the exact compiler error. Then fix it.

Answer
error[E0004]: non-exhaustive patterns: `Shape::Square(_)` not covered
  |
  = help: ensure the match is exhaustive by adding a match arm

This is the feature, not the obstacle: the compiler found every place your new variant needs handling. Never use a _ => ... arm on your own domain enums for exactly this reason — it silently swallows future variants.

🟡 Exercise 7.4 — Simple expression evaluator

Define a recursive enum and evaluate it:

rust
enum Expr {
    Num(f64),
    Add(Box<Expr>, Box<Expr>),
    Sub(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
    Div(Box<Expr>, Box<Expr>),
}

Write fn eval(e: &Expr) -> Option<f64> returning None on division by zero. Evaluate (3 + 4) * 2 and 1 / 0.

Solution
rust
enum Expr {
    Num(f64),
    Add(Box<Expr>, Box<Expr>),
    Sub(Box<Expr>, Box<Expr>),
    Mul(Box<Expr>, Box<Expr>),
    Div(Box<Expr>, Box<Expr>),
}

fn eval(e: &Expr) -> Option<f64> {
    Some(match e {
        Expr::Num(n) => *n,
        Expr::Add(a, b) => eval(a)? + eval(b)?,
        Expr::Sub(a, b) => eval(a)? - eval(b)?,
        Expr::Mul(a, b) => eval(a)? * eval(b)?,
        Expr::Div(a, b) => {
            let d = eval(b)?;
            if d == 0.0 { return None; }
            eval(a)? / d
        }
    })
}

fn main() {
    use Expr::*;
    let e = Mul(Box::new(Add(Box::new(Num(3.0)), Box::new(Num(4.0)))), Box::new(Num(2.0)));
    println!("{:?}", eval(&e));                                     // Some(14.0)
    println!("{:?}", eval(&Div(Box::new(Num(1.0)), Box::new(Num(0.0))))); // None
}

Box is required because a recursive enum would otherwise have infinite size — module 15 explains why in detail.

Part C — Challenges

Longer builds. Expect to fight the borrow checker here; that fight is the lesson.

🔴 Exercise 7.5 — Vending machine state model

Model a vending machine so illegal states are unrepresentable:

  • States: Idle, HasCredit { cents: u32 }, Dispensing { item: String }, OutOfService { reason: String }
  • Events: InsertCoin(u32), SelectItem { name: String, price: u32 }, Refund, Tick
  • Write fn step(state: Machine, event: Event) -> (Machine, Vec<String>) where the Vec holds messages to display. Insufficient credit should not change state but should emit a message. Tick moves Dispensing back to Idle.
Solution
rust
#[derive(Debug, Clone, PartialEq)]
enum Machine {
    Idle,
    HasCredit { cents: u32 },
    Dispensing { item: String },
    OutOfService { reason: String },
}

#[derive(Debug)]
enum Event {
    InsertCoin(u32),
    SelectItem { name: String, price: u32 },
    Refund,
    Tick,
}

fn step(state: Machine, event: Event) -> (Machine, Vec<String>) {
    use Machine::*;
    use Event::*;
    match (state, event) {
        (OutOfService { reason }, _) =>
            (OutOfService { reason: reason.clone() }, vec![format!("out of service: {reason}")]),

        (Idle, InsertCoin(c)) =>
            (HasCredit { cents: c }, vec![format!("credit: {c}c")]),

        (HasCredit { cents }, InsertCoin(c)) =>
            (HasCredit { cents: cents + c }, vec![format!("credit: {}c", cents + c)]),

        (HasCredit { cents }, SelectItem { name, price }) if cents >= price => {
            let change = cents - price;
            let mut msgs = vec![format!("dispensing {name}")];
            if change > 0 { msgs.push(format!("change: {change}c")); }
            (Dispensing { item: name }, msgs)
        }
        (HasCredit { cents }, SelectItem { price, .. }) =>
            (HasCredit { cents }, vec![format!("need {}c more", price - cents)]),

        (HasCredit { cents }, Refund) =>
            (Idle, vec![format!("refunded {cents}c")]),

        (Dispensing { .. }, Tick) => (Idle, vec!["ready".into()]),

        (s, e) => (s, vec![format!("ignored {e:?}")]),
    }
}

fn main() {
    let mut state = Machine::Idle;
    let events = vec![
        Event::InsertCoin(50),
        Event::SelectItem { name: "Cola".into(), price: 75 },
        Event::InsertCoin(50),
        Event::SelectItem { name: "Cola".into(), price: 75 },
        Event::Tick,
    ];
    for e in events {
        let (next, msgs) = step(state, e);
        for m in msgs { println!("{m}"); }
        state = next;
    }
    assert_eq!(state, Machine::Idle);
}

Note the match on the tuple (state, event) — matching two values at once is the canonical way to write a transition table in Rust.

Self-check

  1. Why is enum exhaustiveness a refactoring tool rather than an annoyance?
  2. Why should you avoid _ => {} on your own domain enums?
  3. What must the else block of a let else do?
  4. What's the difference between let _ = v; and let _x = v;?
  5. Why is Option<&T> the same size as &T?
Answers
  1. Adding a variant makes the compiler point at every site that must be updated.
  2. It silently absorbs future variants, defeating the check.
  3. Diverge — return, break, continue, or panic!.
  4. let _ = v; drops v immediately; let _x = v; binds it and keeps it alive to the end of scope.
  5. Niche optimization — a reference can never be null, so the null bit pattern encodes None.

Next: Module 08 — Option, Result & Error Handling