capypad
0 day streak
rust / intermediate
Snippet

Pattern Matching with Enums

Pattern matching with match expressions is Rust's powerful way to handle enums. The compiler ensures all cases are covered, making code exhaustive and safe. Unlike switch statements in other languages, Rust's match must be exhaustive—omitting a case causes a compile error. This eliminates entire categories of bugs at compile time.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#[derive(Debug)]
enum Direction {
North,
South,
East,
West,
}
 
fn move(direction: Direction) -> &'static str {
match direction {
Direction::North => "Moving north",
Direction::South => "Moving south",
Direction::East => "Moving east",
Direction::West => "Moving west",
}
}
 
fn main() {
let heading = Direction::North;
println!("{:?} -> {}", heading, move(heading));
}
Breakdown
1
#[derive(Debug)]
Macro that auto-generates Debug trait implementation for debug printing
2
enum Direction { ... }
Enum defining four directional variants, all unit-like structs
3
fn move(direction: Direction) -> &'static str
Function taking Direction enum and returning a string slice
4
match direction { ... }
Exhaustive pattern match — compiler enforces all variants handled
5
Direction::North => "Moving north"
Pattern arm mapping variant to return value