match basics
- Rust course
- Beginner
- Lesson 37/115
- 4 min
Match a value against patterns with match.
match basics
match compares a value against patterns in order and runs the first arm that matches. Arms are written pattern => expression; patterns can be literals, ranges (1..=5), several values (1 | 2) or _:
let gun = 6;
let tur = match gun {
1..=5 => "iş günü",
6 | 7 => "hafta sonu",
_ => "geçersiz",
};
println!("{tur}");A match must be exhaustive: every possible value must be covered by an arm.
Arm bodies
If an arm runs several lines, curly braces are used; its last expression is the arm's value:
match komut {
"ekle" => {
sayac += 1;
println!("eklendi");
}
"sil" => sayac -= 1,
_ => println!("bilinmeyen: {komut}"),
}Arm order matters: _ goes last, otherwise later arms are never reached and the compiler warns.
Practice Kind of day
Write fn gun_turu(g: u8) -> &'static str: 1–5 "iş günü", 6 and 7 "hafta sonu", otherwise "geçersiz". Print the results for 3, 7 and 9 on separate lines.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn gun_turu(g: u8) -> &'static str {
match g {
1..=5 => "iş günü",
6 | 7 => "hafta sonu",
_ => "geçersiz",
}
}
fn main() {
for g in [3, 7, 9] {
println!("{}", gun_turu(g));
}
}Expected output
iş günü hafta sonu geçersiz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is <code>match</code> safer than a switch?
- The compiler checks that every case is handled Correct answer
- It's faster
- It requires break
- It only works with numbers
Explanation: A missing case is a compile error; also arms don't fall through.
2 Several values
match gun {
6 ____ 7 => "hafta sonu",
_ => "iş günü",
}
match gun {
6 | 7 => "hafta sonu",
_ => "iş günü",
}
Explanation: | combines several patterns in one arm.
3 Pattern and meaning
| Term | Meaning |
|---|---|
3 |
A single value |
1..=5 |
Inclusive range |
6 | 7 |
Several values |
_ |
Everything else |