Summary - Pattern matching
- Rust course
- Beginner
- Lesson 88/115
- 5 min
Combine match, if let and the _ wildcard to build a command interpreter.
Pattern matching summary
match is exhaustive and runs the first arm that fits. Patterns: literals, |, ..= ranges, tuple/struct/enum destructuring, @ binding, _ and ... Use if let for a single pattern, while let for loops, let-else for early exit and matches! for a bool. Arms can also have a guard: x if x < 0 => ...
Match guards
For conditions that a pattern alone can't express, an if is added to the arm:
fn sinif(n: i32) -> &'static str {
match n {
x if x < 0 => "negatif",
0 => "sıfır",
x if x % 2 == 0 => "çift",
_ => "tek",
}
}A guard applies to all patterns joined with |: 1 | 2 if kosul → (1 or 2) and the condition.
Practice Number class
Write the function fn sinif(n: i32) -> &'static str above with match guards. Print the results for -3, 0, 4 and 7 on one line separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn sinif(n: i32) -> &'static str {
match n {
x if x < 0 => "negatif",
0 => "sıfır",
x if x % 2 == 0 => "çift",
_ => "tek",
}
}
fn main() {
println!("{} {} {} {}", sinif(-3), sinif(0), sinif(4), sinif(7));
}Expected output
negatif sıfır çift tek
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is needed for exhaustiveness when using guarded arms?
- Usually an unguarded final arm (like _) Correct answer
- Nothing; the compiler solves the conditions
- A guard on every arm
- An else block
Explanation: The compiler doesn't evaluate guard expressions, so an unguarded arm must cover the remaining cases.
2 Add a guard
match n {
x ____ x < 0 => "negatif",
_ => "pozitif ya da sıfır",
}
match n {
x if x < 0 => "negatif",
_ => "pozitif ya da sıfır",
}
Explanation: A match guard is written with if after the pattern.
3 sinif() input and result
| Term | Meaning |
|---|---|
-3 |
negatif |
0 |
sıfır |
4 |
çift |
7 |
tek |