beginnerFlow Control
Match with Enums
Pattern match on enum variants with data extraction.
Match with Enums
Pattern match on enum variants with data extraction.
Difficulty
Beginner
Code
rust
enum Direction {
North,
South,
East,
West,
}
fn compass(d: &Direction) -> &str {
match d {
Direction::North => "going up",
Direction::South => "going down",
Direction::East => "going right",
Direction::West => "going left",
}
}
fn main() {
let d = Direction::North;
println!("{}", compass(&d));
// match with Option
let x: Option<i32> = Some(42);
match x {
Some(n) if n > 100 => println!("big: {}", n),
Some(n) => println!("small: {}", n),
None => println!("none"),
}
}Explanation
Match on enum variants to extract data.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the flow-control category to build a complete understanding of this topic.