An enum lists variants that can carry data. match reads the active variant and its values.

Program

Play the program to compute the area of a square variant.

enums.rs
Replay: real traced execution (multi-file project)
enum Shape {
    Circle(f64),
    Square(f64),
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(r) => 3.14 * r * r,
        Shape::Square(s) => s * s,
    }
}

fn main() {
    let shape = Shape::Square(3.0);
    let a = area(&shape);
    println!("{a}");
}
  1. shape ← (empty)

    13fn main() {14    let shap→ (empty)e = Shape::Square(3.0);15    let a = area(&shap(empty)e);16    println!("{a}");
  2. a ← 9.0

    14    let shape = Shape::Square(3.0);15    let → 9.0a = area(&shap(empty)e);16    println!("{a}");17}
    output9

Follow the Trace

  1. main builds Shape::Square(3.0).
  2. area(&shape) receives that square.
  3. The match chooses the Shape::Square(s) arm.
  4. s is 3.0, so the return value is 9.
  5. a becomes 9, and the program prints 9. | trace point | value | | --- | --- | | shape | Square(3.0) | | matched arm | Shape::Square(s) | | s | 3.0 | | returned area | 9 | | stdout | 9 |
enum `enum Shape` defines alternative variants.
variant data `Square(f64)` carries a value inside the variant.
match variant `match` binds the inner value, like `s`.

Exercise: enums.rs

Reproduce the output 9, then trace which enum variant and inner value make the square area.