1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# Guards
A `match` *guard* can be added to filter the arm.
```rust,editable
enum Temperature {
Celsius(i32),
Farenheit(i32),
}
fn main() {
let temperature = Temperature::Celsius(35);
// ^ TODO try different values for `temperature`
match temperature {
Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t),
// The `if condition` part ^ is a guard
Temperature::Celsius(t) => println!("{}C is below 30 Celsius", t),
Temperature::Farenheit(t) if t > 86 => println!("{}F is above 86 Farenheit", t),
Temperature::Farenheit(t) => println!("{}F is below 86 Farenheit", t),
}
}
```
Note that the compiler won't take guard conditions into account when checking
if all patterns are covered by the match expression.
```rust,editable,ignore,mdbook-runnable
fn main() {
let number: u8 = 4;
match number {
i if i == 0 => println!("Zero"),
i if i > 0 => println!("Greater than zero"),
// _ => unreachable!("Should never happen."),
// TODO ^ uncomment to fix compilation
}
}
```
### See also:
[Tuples](../../primitives/tuples.md)
[Enums](../../custom_types/enum.md)
|