Skip to content

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.

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:

Wednesday
▶ Try it Yourself

The _ 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.”

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"),
}
}
▶ Try it Yourself

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"),
}
}
▶ Try it Yourself

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}");
}
▶ Try it Yourself

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.

  • match compares 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, like if, can be used as an expression to produce a value.

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