title: Match Statements
match is Rust’s pattern matching construct — like a switch statement but much more powerful. It must be exhaustive: every possible case must be covered or the compiler will error.
Basic syntax
match value {
pattern1 => expression1,
pattern2 => expression2,
_ => fallback, // wildcard, matches anything
}Matching literals
let x = 3;
match x {
1 => println!("one"),
2 | 3 => println!("two or three"), // multiple patterns with |
4..=6 => println!("four to six"), // inclusive range
_ => println!("something else"),
}Matching enums
enum Direction { North, South, East, West }
match dir {
Direction::North => println!("going north"),
Direction::South => println!("going south"),
_ => println!("going east or west"),
}Destructuring
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
}
match msg {
Message::Quit => println!("quit"),
Message::Move { x, y } => println!("move to {x}, {y}"),
Message::Write(text) => println!("write: {text}"),
}match as an expression
match returns a value, so it can be assigned directly:
let description = match x {
1 => "one",
2 => "two",
_ => "other",
};Guards
Add extra conditions to a pattern with if:
match x {
n if n < 0 => println!("negative"),
n if n == 0 => println!("zero"),
_ => println!("positive"),
}