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
- Defining Your First Enum
- Matching on Enum Variants
- Enums with Data
- Match Guards and Bindings