TExcelTAD
Home › Rust › Rust Enums

Rust Enums

An enum (short for enumeration) is a type whose value is exactly one of a fixed set of variants. A traffic light is red, yellow or green; a payment is cash, card or voucher. Enums let you express that "one of these" idea directly, and the compiler then makes sure you handle every case.

Defining a simple enum

rust · try it yourself
#[derive(Debug)]
enum Direction {
    North,
    East,
    South,
    West,
}

fn main() {
    let heading = Direction::East;
    let opposite = Direction::West;

    println!("Heading {:?}, turning to {:?}", heading, opposite);
}
Heading East, turning to West

Variants are written with the enum name and ::, as in Direction::East. Each variant is a possible value of the type Direction.

Using match with enums

match is the natural partner of enums. It compares a value against each variant and runs the matching arm. The compiler checks that the match is exhaustive — if you forget a variant, your code will not compile.

rust · try it yourself
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter,
}

fn cents(coin: &Coin) -> u32 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter => 25,
    }
}

fn main() {
    let purse = [Coin::Quarter, Coin::Dime, Coin::Penny, Coin::Penny];
    let mut total = 0;
    for c in &purse {
        total += cents(c);
    }
    println!("The purse holds {} cents", total);
}
The purse holds 37 cents

Forget Coin::Quarter and you get:

text
error[E0004]: non-exhaustive patterns: `&Coin::Quarter` not covered

Variants that carry data

This is where Rust enums become much more powerful than in many other languages: each variant can hold its own data, with different types and amounts per variant.

rust · try it yourself
enum Shape {
    Circle(f64),               // radius
    Rectangle(f64, f64),       // width, height
    Triangle { base: f64, height: f64 },
}

fn area(shape: &Shape) -> f64 {
    match shape {
        Shape::Circle(r) => 3.14 * r * r,
        Shape::Rectangle(w, h) => w * h,
        Shape::Triangle { base, height } => 0.5 * base * height,
    }
}

fn main() {
    let shapes = vec![
        Shape::Circle(2.0),
        Shape::Rectangle(3.0, 4.0),
        Shape::Triangle { base: 6.0, height: 5.0 },
    ];

    for s in &shapes {
        println!("Area: {:.2}", area(s));
    }
}
Area: 12.56
Area: 12.00
Area: 15.00

In each match arm, the pattern pulls out the data stored in the variant (r, w, h, …) so you can use it. A Vec<Shape> can mix all three kinds of shapes, because they are all the same type.

Variant style Example How to match it
No data Quit Msg::Quit => ...
Tuple-like Move(i32, i32) Msg::Move(x, y) => ...
Struct-like Write { text: String } Msg::Write { text } => ...

Methods on enums

Just like structs, enums can have an impl block with methods.

rust · try it yourself
enum Command {
    Say(String),
    Add(i32, i32),
    Quit,
}

impl Command {
    fn run(&self) -> String {
        match self {
            Command::Say(text) => format!("You said: {}", text),
            Command::Add(a, b) => format!("{} + {} = {}", a, b, a + b),
            Command::Quit => String::from("Goodbye!"),
        }
    }

    fn is_quit(&self) -> bool {
        matches!(self, Command::Quit)
    }
}

fn main() {
    let script = [
        Command::Say(String::from("hello")),
        Command::Add(4, 9),
        Command::Quit,
    ];

    for cmd in &script {
        println!("{}", cmd.run());
        if cmd.is_quit() {
            println!("(stopping)");
        }
    }
}
You said: hello
4 + 9 = 13
Goodbye!
(stopping)

matches! is a handy macro that returns true if a value fits a pattern.

if let: when you care about one variant

If you only want to react to one variant and ignore the rest, if let is shorter than a full match:

rust · try it yourself
enum Event {
    KeyPress(char),
    Click { x: i32, y: i32 },
    Resize,
}

fn main() {
    let events = [Event::Resize, Event::KeyPress('q'), Event::Click { x: 10, y: 20 }];

    for e in &events {
        if let Event::KeyPress(c) = e {
            println!("Key pressed: {}", c);
        } else if let Event::Click { x, y } = e {
            println!("Clicked at ({}, {})", x, y);
        } else {
            println!("Some other event");
        }
    }
}
Some other event
Key pressed: q
Clicked at (10, 20)

Enums you already know

The standard library is full of enums. The two most important ones are Option<T> (a value that may be missing: Some(v) or None) and Result<T, E> (success Ok(v) or failure Err(e)). They get their own lesson next.

Tip: Whenever you catch yourself using strings or numbers like "admin", "guest" or 0, 1, 2 to mean "kind of thing", consider an enum. Typos become compile errors instead of bugs.

Test yourself

How do you refer to the Red variant of an enum named Color?

  1. Color.Red
  2. Color::Red
  3. Red::Color
  4. Color[Red]

What happens if a match on an enum does not handle every variant?

  1. The missing variants are ignored
  2. It panics at runtime
  3. The program does not compile
  4. It returns None

Which statement about enum variants is true?

  1. All variants must hold the same data type
  2. Variants can hold no data, tuple-like data or named fields
  3. Variants cannot hold data
  4. Only one variant may hold data