Guard
- Rust course
- Advanced
- Lesson 75/81
- 4 min
Add a condition to a pattern with if guard.
Guards
Conditions that a pattern can't express (like a relation between two bound variables) are added to the end of the arm with if:
fn iliski(c: (i32, i32)) -> &'static str {
match c {
(a, b) if a == b => "eşit",
(a, b) if a + b == 0 => "zıt",
_ => "farklı",
}
}Guards can also reach outer variables: Some(x) if x == hedef. Writing an outer variable's name inside the pattern, however, means a new binding, not a comparison; this is a common mistake.
Guards and exhaustiveness
The compiler doesn't evaluate guard conditions, so guarded arms don't count toward the exhaustiveness check and an unconditional arm is usually needed at the end:
match n {
x if x < 0 => "negatif",
x if x >= 0 => "pozitif ya da sıfır",
_ => unreachable!(), // the compiler doesn't know the two conditions cover everything
}In such cases it's better to write the patterns as ranges: i32::MIN..=-1 and 0...
Practice Relation
Write the iliski function above with guards. Print the results for (2, 2), (3, -3) and (1, 5) on one line separated by spaces.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn iliski(c: (i32, i32)) -> &'static str {
match c {
(a, b) if a == b => "eşit",
(a, b) if a + b == 0 => "zıt",
_ => "farklı",
}
}
fn main() {
println!("{} {} {}", iliski((2, 2)), iliski((3, -3)), iliski((1, 5)));
}Expected output
eşit zıt farklı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>let hedef = 5; match v { Some(hedef) => .., _ => .. }</code> do?
- Matches every Some value and creates a new hedef variable (shadowing) Correct answer
- Matches only Some(5)
- It doesn't compile
- Panic
Explanation: A name in a pattern is always a new binding; for comparison write Some(x) if x == hedef.
2 Conditional arm
match c {
(a, b) ____ a == b => "eşit",
_ => "farklı",
}
match c {
(a, b) if a == b => "eşit",
_ => "farklı",
}
Explanation: A guard is written with if after the pattern.
3 Pair and result
| Term | Meaning |
|---|---|
(2, 2) |
eşit |
(3, -3) |
zıt |
(1, 5) |
farklı |
(0, 0) |
eşit (first arm) |