FerrousPath

Level 1 · Foundations· Lesson 7 of 10 · 25 min

Enums and pattern matching

Types that are one of several shapes, Option instead of null, and match as an exhaustive case analysis.

Enums carry data

An enum is a type whose value is exactly one of several variants. Unlike enums in C, each variant can carry its own data.

#[derive(Debug)]
enum Shape {
    Circle { radius: f64 },
    Rectangle { width: f64, height: f64 },
    Triangle(f64, f64, f64),
    Point,
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
        Shape::Rectangle { width, height } => width * height,
        Shape::Triangle(a, b, c) => {
            let s = (a + b + c) / 2.0;
            (s * (s - a) * (s - b) * (s - c)).sqrt()
        }
        Shape::Point => 0.0,
    }
}

fn main() {
    let shapes = [
        Shape::Circle { radius: 1.0 },
        Shape::Rectangle { width: 2.0, height: 3.0 },
        Shape::Triangle(3.0, 4.0, 5.0),
        Shape::Point,
    ];
    for s in &shapes {
        println!("{s:?} has area {:.2}", area(s));
    }
}

Structs are “this and this and this”. Enums are “this or this or this”. Together they are called algebraic data types, and modelling your domain with them — so that invalid states simply cannot be constructed — is the most valuable design habit in Rust.

match is exhaustive

Add a variant Square(f64) to Shape above and run it. The compiler refuses until area handles it. Every match in your program that needs updating becomes a compile error pointing at itself. Avoid a _ wildcard on your own enums for exactly this reason.

Patterns can do more than name variants:

fn classify(n: i32) -> &'static str {
    match n {
        0 => "zero",
        1 | 2 | 3 => "small",
        4..=99 => "medium",
        x if x < 0 => "negative",   // a guard
        _ => "large",
    }
}

fn main() {
    for n in [0, 2, 50, -7, 1000] {
        println!("{n}: {}", classify(n));
    }

    let point = (0, -3);
    match point {
        (0, 0) => println!("origin"),
        (x, 0) => println!("on the x axis at {x}"),
        (0, y) => println!("on the y axis at {y}"),
        (x, y) => println!("at ({x}, {y})"),
    }
}

Option: there is no null

Tony Hoare called null references his “billion-dollar mistake”: any reference might secretly be nothing, and the type system does not say which. Rust has no null. A value that may be absent has a different type:

enum Option<T> {
    Some(T),
    None,
}

Option<T> and its variants are always in scope. An Option<i32> is not an i32 — you cannot add to it or print it as a number until you have dealt with the None case.

fn divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 { None } else { Some(a / b) }
}

fn main() {
    match divide(10, 2) {
        Some(q) => println!("quotient {q}"),
        None => println!("cannot divide by zero"),
    }

    // Useful methods so you do not always need a match:
    println!("{}", divide(1, 0).unwrap_or(0));
    println!("{:?}", divide(9, 3).map(|q| q * 100));
    println!("{}", divide(1, 0).is_none());
}

unwrap() extracts the value or panics on None. It is acceptable in examples and tests, or where None is truly impossible; in real code prefer match, unwrap_or, ? (next lessons) or expect("why this cannot fail").

if let, let else, and while let

When only one pattern matters:

fn parse_port(s: &str) -> u16 {
    // let-else: bind on success, or diverge (return/break/panic) on failure.
    let Ok(port) = s.parse::<u16>() else {
        return 8080;
    };
    port
}

fn main() {
    let favourite: Option<&str> = Some("teal");
    if let Some(colour) = favourite {
        println!("favourite colour: {colour}");
    } else {
        println!("no favourite");
    }

    println!("{} {}", parse_port("3000"), parse_port("not a number"));

    let mut stack = vec![1, 2, 3];
    while let Some(top) = stack.pop() {
        println!("popped {top}");
    }
}

Enums have methods too

#[derive(Debug, Clone, Copy, PartialEq)]
enum Light {
    Red,
    Green,
    Amber,
}

impl Light {
    fn next(self) -> Light {
        match self {
            Light::Red => Light::Green,
            Light::Green => Light::Amber,
            Light::Amber => Light::Red,
        }
    }
}

fn main() {
    let mut light = Light::Red;
    for _ in 0..4 {
        print!("{light:?} → ");
        light = light.next();
    }
    println!("{light:?}");
}

Exercises

  1. Define enum Coin { Penny, Nickel, Dime, Quarter } and fn cents(c: Coin) -> u32.
  2. Write fn first_even(xs: &[i32]) -> Option<i32>.
  3. Model a text-editor command: Insert(char), Delete, MoveTo { line: usize, col: usize }, Quit. Write fn describe(c: &Command) -> String.
Solution to 2
fn first_even(xs: &[i32]) -> Option<i32> {
    for &x in xs {
        if x % 2 == 0 {
            return Some(x);
        }
    }
    None
}

fn main() {
    println!("{:?} {:?}", first_even(&[1, 3, 4, 6]), first_even(&[1, 3]));
}

Later you will write this as xs.iter().copied().find(|x| x % 2 == 0).

Check your understanding

Pick an answer to see the explanation.

  1. 1.How does Rust represent a value that may be absent?

  2. 2.What happens if a match on an enum omits one variant and has no wildcard arm?

  3. 3.When is if let preferable to match?

Key terms in this lesson

Finished the lesson and the exercises?