Pattern Matching with match
match lets your program compare a value against several possible options and run different code for each one.Basic match
match compares a value against a list of patterns in order and executes the code for the first pattern that matches. It is Rust's primary tool for branching on more than two possibilities.
Example: Basic match
fn main() {
let day = 3;
match day {
1 => println!("Monday"),
2 => println!("Tuesday"),
3 => println!("Wednesday"),
_ => println!("Some other day"),
}
}
Login to try C/C++/Java/PHP code in the editor
Exhaustiveness
The Rust compiler requires every match to cover all possible values of the matched type. The _ wildcard pattern is a catch-all that satisfies this requirement for any values not explicitly listed.
Example: Exhaustiveness
fn main() {
let letter_grade = 'B';
match letter_grade {
'A' => println!("Excellent"),
'B' => println!("Good"),
'C' => println!("Average"),
_ => println!("Needs improvement"),
}
}
Login to try C/C++/Java/PHP code in the editor
Matching Multiple Values
The | operator inside a pattern lets a single match arm handle several distinct values at once, avoiding repeated arms with identical code.
Example: Matching Multiple Values
fn main() {
let n = 4;
match n {
1 | 3 | 5 | 7 => println!("{} is odd (from list)", n),
2 | 4 | 6 | 8 => println!("{} is even (from list)", n),
_ => println!("Out of range"),
}
}
Login to try C/C++/Java/PHP code in the editor
match as an Expression
Like if, match is an expression and can produce a value directly, which is commonly assigned to a variable instead of duplicating logic across arms.
Example: match as an Expression
fn main() {
let number = 6;
let description = match number % 2 {
0 => "even",
_ => "odd",
};
println!("{} is {}", number, description);
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting that
matchin Rust must be exhaustive -- every possible value of the type must be covered, or it won't compile. - Using
_too early in a match, accidentally catching cases that should have been handled by a more specific arm listed after it. - Trying to fall through between match arms like a C
switchstatement -- Rust'smatcharms never fall through.
matchcompares a value against a series of patterns and runs the code for the first one that matches.- Matches must be exhaustive; the
_wildcard pattern catches any remaining cases. - Multiple values can share one arm using the
|pattern, e.g.1 | 2 => .... matchis an expression, so it can produce a value just likeif.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: