C.W.K.
Stream
Lesson 01 of 06 · published

Enums — One of Several

~11 min · enums, sum-type, variants

Level 0Rust Curious
0 XP0/80 lessons0/19 achievements
0/100 XP to next level100 XP to go0% complete

A struct says 'all of these at once.' An enum says 'exactly one of these.' That flip — from AND to OR — unlocks a way of modeling data that's central to idiomatic Rust.

Variants, with or without data

An enum lists named variants. A value of the enum is one variant at a time. The trick that makes Rust enums powerful: each variant can carry its own data, of its own shape. One variant can be empty, another can hold a tuple, another a struct-like set of fields — all under one type.

Why this is called a sum type

A struct is a 'product type' — its set of possible values is the product of its fields' possibilities. An enum is a 'sum type' — its possible values are the sum of its variants. This isn't academic: it's the tool for modeling a value that is genuinely one-of-several, like a message that's either Quit, or a Move with coordinates, or Text with a string.

Enums make illegal states unrepresentable. If a value can only be one of three real states, an enum with three variants means the fourth, invalid state literally cannot be constructed. You stop writing defensive checks for cases the type system already forbids.

Enums get methods too

Just like structs, enums can have impl blocks with methods. A method on an enum typically starts with a match self to do different things per variant — which is exactly what the next lessons build toward.

Code

One enum, four differently-shaped variants·rust
enum Message {
    Quit,                        // no data
    Move { x: i32, y: i32 },     // struct-like fields
    Write(String),               // a single value
    ChangeColor(i32, i32, i32),  // a tuple of values
}

impl Message {
    fn describe(&self) -> &str {
        match self {
            Message::Quit => "quit",
            Message::Move { .. } => "move",
            Message::Write(_) => "write",
            Message::ChangeColor(..) => "color",
        }
    }
}

fn main() {
    let m = Message::Write(String::from("hi"));
    println!("{}", m.describe());
}

External links

Exercise

Model a traffic light as an enum with three variants. Add a variant that carries data — say a Custom(u8, u8, u8) for an RGB color. Write a method that returns how many seconds each light lasts. Why is an enum a better model here than three booleans?
Hint
Three booleans could encode impossible states (red AND green at once). An enum makes the light exactly one color at a time — the illegal combinations can't be built.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Ttoriwarm

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.