Course contentsShow
← Rust
Lesson 44 of 1,9101. Rust Fundamentals and ToolingFree lesson

Enumerated Types and Variants

Use sum types to represent mutually exclusive state and enforce exhaustive logic.

In this lesson, you will learn how to use enumerated types to group mutually exclusive states and force your code to handle every possibility safely.

Beyond Simple Structs

So far, you’ve used structs to bundle data together. But sometimes, data isn't a collection of fields—it’s a choice between different, mutually exclusive options. This is where enum comes in.

An enum defines a type by listing its possible variants. For example, consider a traffic light:

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

Here, a TrafficLight can only ever be one of these three states. Unlike a struct, which holds all its fields at once, an enum represents sum types: it holds exactly one of the variants at any given time.

Enforcing Exhaustive Logic

The true power of enums appears when you want to act on them. Rust forces you to be exhaustive, meaning you cannot forget to handle a state. Using a match expression, you define what happens for every possible variant:

fn get_action(light: TrafficLight) {
    match light {
        TrafficLight::Red => println!("Stop!"),
        TrafficLight::Yellow => println!("Caution!"),
        TrafficLight::Green => println!("Go!"),
    }
}

If you were to add a new variant, like TrafficLight::FlashingRed, your code would stop compiling until you update the match block to handle it. This creates a "safety net" that prevents logic bugs where a specific state is ignored.

Why use Enums?

Using enums is much safer than using "magic numbers" (like setting an integer 1 for Red and 2 for Green). If you used an integer, you would have to manually check for invalid numbers (like 99) and handle them. With an enum, the compiler guarantees that only your defined variants exist. By restricting the state space to only what is valid, you eliminate entire categories of bugs related to undefined or unexpected data states.

Key Takeaway: Enums represent mutually exclusive states, and Rust’s exhaustive matching ensures that you explicitly handle every possible variant, making your logic bulletproof.