match patterns
- Rust course
- Beginner
- Lesson 83/115
- 4 min
Match against different patterns with match.
match patterns
match compares a value against patterns listed as arms; the first arm that fits runs. Patterns can be a literal value, several values with |, or a range with ..=:
fn harf_notu(p: u8) -> char {
match p {
90..=100 => 'A',
70..=89 => 'B',
50..=69 => 'C',
_ => 'F',
}
}match is an expression; all arms must produce a value of the same type.
Multiple values and blocks
With |, several patterns join in one arm. If an arm's body is several lines, braces are used; the last expression is the arm's value:
let gun = 6;
let tur = match gun {
1 | 2 | 3 | 4 | 5 => "iş",
6 | 7 => {
println!("tatil!");
"hafta sonu"
}
_ => "geçersiz",
};Practice Letter grade
Write the function fn harf_notu(p: u8) -> char above with range patterns. Print the results for 95, 72 and 40 separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn harf_notu(p: u8) -> char {
match p {
90..=100 => 'A',
70..=89 => 'B',
50..=69 => 'C',
_ => 'F',
}
}
fn main() {
println!("{} {} {}", harf_notu(95), harf_notu(72), harf_notu(40));
}Expected output
A B F
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if the arms are written in the order <code>_ => 'F', 90..=100 => 'A'</code>?
- One is picked at random
- Every value becomes F; the compiler warns about an unreachable arm Correct answer
- Compile error
- Order doesn't matter
Explanation: Arms are tried from top to bottom; since _ fits everything, the later arms never run.
2 Range pattern
match p {
90____100 => 'A',
_ => 'F',
}
match p {
90..=100 => 'A',
_ => 'F',
}
Explanation: In patterns an inclusive range is written with ..=.
3 Score and harf_notu result
| Term | Meaning |
|---|---|
95 |
A |
72 |
B |
50 |
C |
40 |
F |