0PricingLogin
Learn Rust Coding · Lesson

Matching on Enum Variants

Use match to handle each case.

Meet the match Expression

The match expression compares a value against a series of patterns and runs the code for the first one that fits.

It is the natural partner of enums: you can handle each variant in its own arm.

enum Light {
    Red,
    Green,
}

fn action(l: Light) {
    match l {
        Light::Red => println!("Stop"),
        Light::Green => println!("Go"),
    }
}

Anatomy of a match Arm

Each arm has the form pattern => expression, and arms are separated by commas.

The pattern is what to match, and the expression after => runs when it matches. Here the pattern is a single enum variant.

match light {
    Light::Red => println!("Stop"),
    Light::Green => println!("Go"),
}

All lessons in this course

  1. Defining Your First Enum
  2. Matching on Enum Variants
  3. Enums with Data
  4. Match Guards and Bindings
← Back to Learn Rust Coding