Skip to content

Represent Alternatives with an Enum

The Course
•
26 min study

Some values can only be one of a few things. A study session is practice or review; it is planned or done. You could store that as a String, but then "Done", "done" and "dnoe" are all valid strings, and nothing stops a typo from slipping through. You could store a bool, but true does not say what it means, and a third kind of session would not fit. An enum lists the allowed alternatives, called variants, as a type of its own. A value of Kind is always exactly one of its variants.

To act on an enum, use match. It compares the value with each pattern from top to bottom and runs the first arm that matches. The compiler also checks that the arms cover every variant, so no case can be forgotten. Here each arm produces a string literal, so the function returns &'static str. The 'static means the text is built into the program and stays available for its whole run.

Predict and run

Which arm handles each call?

Predict, then run Rust
enum Kind {
    Practice,
    Review,
}

fn label(kind: &Kind) -> &'static str {
    match kind {
        Kind::Practice => "hands-on",
        Kind::Review => "recall",
    }
}

fn main() {
    println!("{}", label(&Kind::Review));
    println!("{}", label(&Kind::Practice));
}
Check your prediction
Text
recall
hands-on

Variants are written with the enum's name and two colons, Kind::Review. The order of the calls decides the order of the output; the order of the arms only matters when more than one pattern could match.

Now add a Reading variant to the enum and run without changing label. The program no longer compiles:

Text
error[E0004]: non-exhaustive patterns: `&Kind::Reading` not covered

This is the main reason to use an enum. Adding a variant turns every match that does not handle it into an error, so the compiler lists the places you need to update. Add an arm for Reading with its own label and run again.

match produces a value

A match is an expression, so its result can go straight into a binding. Every arm must then produce the same type. When several variants should be treated alike, the wildcard pattern _ matches anything that earlier arms did not.

Choose a break length Rust
enum Kind {
    Practice,
    Review,
    Reading,
}

fn break_minutes(kind: &Kind) -> u32 {
    match kind {
        Kind::Practice => 10,
        _ => 5,
    }
}

fn main() {
    let kinds = vec![Kind::Practice, Kind::Review, Kind::Reading];
    let mut total = 0;
    for kind in &kinds {
        total += break_minutes(kind);
    }
    println!("Breaks: {total} minutes");
}
Text
Breaks: 20 minutes

The wildcard is convenient, but it gives up the safety you just saw. A new variant added later falls into _ silently instead of producing an error. Prefer listing variants by name when each one deserves a decision.

Variants can carry data

A variant can hold values, written in parentheses after its name. A finished session might record how long it actually took, while a planned one has nothing to record yet. In the pattern, a name such as minutes binds the value inside, ready to use in that arm.

Record actual minutes on Done Rust
enum Status {
    Planned,
    Done(u32),
}

fn describe(status: &Status) {
    match status {
        Status::Planned => println!("Not started"),
        Status::Done(minutes) => println!("Finished in {minutes} min"),
    }
}

fn main() {
    describe(&Status::Planned);
    describe(&Status::Done(35));
}
Text
Not started
Finished in 35 min

A planned session has no duration at all, so there is no meaningless placeholder such as 0 to misread. Because status is a reference, minutes is a reference too; println! reads through it for you. Tomorrow you will meet two enums from the standard library built exactly this way: Option and Result.

Let the compiler find the cases

When you add a variant, run the program before writing any new code. Each non-exhaustive patterns error is a place that needs a decision.

Practice

Exercise

Your turn

Create an enum with Planned and Done. Write show to borrow a status and print Up next or Finished. Call it once for each status.

Your working space Rust
// Define the Status enum and the show function here.

fn main() {
    // Call show once for each variant.
}
Hint 1: the idea

Match the borrowed status and handle both variants.

Hint 2: a first step

Write the enum first, one line per variant, and run the program: it should still compile. Then write the signature of show, choosing the parameter type that borrows a Status instead of taking it.

Worked solution
Run the solution Rust
enum Status {
    Planned,
    Done,
}

fn show(status: &Status) {
    match status {
        Status::Planned => println!("Up next"),
        Status::Done => println!("Finished"),
    }
}

fn main() {
    show(&Status::Planned);
    show(&Status::Done);
}
Text
Up next
Finished

Here each arm prints instead of producing a value, so show has no return type. Both shapes are common: return a value when the caller decides what to do with it, print inside the arms when the function's whole job is output. The checkpoint combines this enum with a struct and a vector.

Was this article helpful?

Your response is saved on this device.