RustEnums & Pattern Matching
Match Expressions
match is Rust's pattern-matching workhorse. Every possible case has to be handled, and the compiler holds you to it.
Basic Match
rust
enum Coin { Penny, Nickel, Dime, Quarter,}
fn value_in_cents(coin: &Coin) -> u32 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, }}Exhaustiveness
Match must cover all variants:
rust
// ERROR: non-exhaustive patterns (missing Dime, Quarter)// match coin {// Coin::Penny => 1,// Coin::Nickel => 5,// }Use _ as a catch-all:
rust
match coin { Coin::Penny => println!("Lucky penny!"), _ => println!("Not a penny"),}Watch both sides of that trade. Exhaustiveness catches a missing arm, but a catch-all hides the next variant you add, which is how a forgotten state slips through a protocol handler.
Try itDelete the Coin::Quarter arm and run. Then add _ => 0 in its place, add a HalfDollar variant, put one in the purse and notice that nothing complains.
Rust (1.40.0)
Matching with Data
rust
enum Message { Quit, Echo(String), Move { x: i32, y: i32 }, Color(i32, i32, i32),}
fn process(msg: Message) { match msg { Message::Quit => println!("Quitting"), Message::Echo(text) => println!("Echo: {}", text), Message::Move { x, y } => println!("Moving to ({}, {})", x, y), Message::Color(r, g, b) => println!("Color: ({}, {}, {})", r, g, b), }}Key Concept
Pattern matching pulls the variant apart and hands you its data directly. The compiler checks that every variant is covered and that you read it the right way. Far safer than a switch whose default quietly absorbs every new variant you forget to handle.
Match Guards
Add conditions to match arms:
rust
let num = 4;match num { n if n < 0 => println!("Negative"), 0 => println!("Zero"), n if n % 2 == 0 => println!("Positive even: {}", n), n => println!("Positive odd: {}", n),}Matching Multiple Patterns
rust
let x = 1;match x { 1 | 2 => println!("One or two"), 3..=5 => println!("Three through five"), _ => println!("Something else"),}if let
When only one variant matters to you, if let trims the noise:
rust
let config_max = Some(3u8);
// Instead of:match config_max { Some(max) => println!("Max: {}", max), _ => (),}
// Use:if let Some(max) = config_max { println!("Max: {}", max);}while let
Loop until a pattern stops matching:
rust
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() { println!("{}", top);}// Prints: 3, 2, 1