Rust Match
match compares a value against a list of patterns and runs the code for whichever one fits. Think of it as a more powerful version of a switch statement, if you’ve used one before — and if you haven’t, it’s still one of the more useful patterns to learn early.
Basic match
Section titled “Basic match”fn main() { let day = 3;
match day { 1 => println!("Monday"), 2 => println!("Tuesday"), 3 => println!("Wednesday"), 4 => println!("Thursday"), 5 => println!("Friday"), _ => println!("Weekend"), }}Output:
WednesdayThe _ is a catch-all — it matches anything not listed above it. match requires every possible value to be handled, so _ is usually there to cover “everything else.”
Matching multiple values at once
Section titled “Matching multiple values at once”You can group several values into one arm using |:
fn main() { let day = 6;
match day { 1 | 2 | 3 | 4 | 5 => println!("Weekday"), 6 | 7 => println!("Weekend"), _ => println!("Not a valid day"), }}Matching a range
Section titled “Matching a range”For numbers, you can match a whole range with ..=:
fn main() { let score = 85;
match score { 90..=100 => println!("A"), 75..=89 => println!("B"), 60..=74 => println!("C"), _ => println!("F"), }}match as an expression
Section titled “match as an expression”Just like if, match can produce a value:
fn main() { let day = 6;
let kind = match day { 1 | 2 | 3 | 4 | 5 => "weekday", 6 | 7 => "weekend", _ => "unknown", };
println!("{kind}");}match vs if/else
Section titled “match vs if/else”Either works for simple true/false checks, but match starts to win once you have more than two or three possibilities — it reads better than a long chain of else if, and the compiler checks you’ve covered every case. if/else is still the right tool for a single yes/no condition.
matchcompares a value against patterns and runs the matching arm.- Every possible value must be handled — use
_as a catch-all. - Combine values with
|, or match a range with..=. match, likeif, can be used as an expression to produce a value.
Quick check
Section titled “Quick check”Quick check
1. What does the _ pattern do in a match expression?
2. What happens if a match expression doesn't handle every possible value and has no _ arm?
3. How do you match several values in one arm, like 1, 2, or 3?
Score: 0 / 3