|
3 | 3 | A `match` *guard* can be added to filter the arm.
|
4 | 4 |
|
5 | 5 | ```rust,editable
|
| 6 | +enum Temperature { |
| 7 | + Celsius(i32), |
| 8 | + Farenheit(i32), |
| 9 | +} |
| 10 | +
|
6 | 11 | fn main() {
|
7 |
| - let pair = (2, -2); |
8 |
| - // TODO ^ Try different values for `pair` |
9 |
| -
|
10 |
| - println!("Tell me about {:?}", pair); |
11 |
| - match pair { |
12 |
| - (x, y) if x == y => println!("These are twins"), |
13 |
| - // The ^ `if condition` part is a guard |
14 |
| - (x, y) if x + y == 0 => println!("Antimatter, kaboom!"), |
15 |
| - (x, _) if x % 2 == 1 => println!("The first one is odd"), |
16 |
| - _ => println!("No correlation..."), |
| 12 | + let temperature = Temperature::Celsius(35); |
| 13 | + // ^ TODO try different values for `temperature` |
| 14 | +
|
| 15 | + match temperature { |
| 16 | + Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t), |
| 17 | + // The `if condition` part ^ is a guard |
| 18 | + Temperature::Celsius(t) => println!("{}C is below 30 Celsius", t), |
| 19 | +
|
| 20 | + Temperature::Farenheit(t) if t > 86 => println!("{}F is above 86 Farenheit", t), |
| 21 | + Temperature::Farenheit(t) => println!("{}F is below 86 Farenheit", t), |
17 | 22 | }
|
18 | 23 | }
|
19 | 24 | ```
|
20 | 25 |
|
21 |
| -Note that the compiler does not check arbitrary expressions for whether all |
22 |
| -possible conditions have been checked. Therefore, you must use the `_` pattern |
23 |
| -at the end. |
| 26 | +Note that the compiler won't take guard conditions into account when checking |
| 27 | +if all patterns are covered by the match expression. |
24 | 28 |
|
25 |
| -```rust,editable |
| 29 | +```rust,editable,ignore,mdbook-runnable |
26 | 30 | fn main() {
|
27 | 31 | let number: u8 = 4;
|
28 | 32 |
|
29 | 33 | match number {
|
30 | 34 | i if i == 0 => println!("Zero"),
|
31 | 35 | i if i > 0 => println!("Greater than zero"),
|
32 |
| - _ => println!("Fell through"), // This should not be possible to reach |
| 36 | + // _ => unreachable!("Should never happen."), |
| 37 | + // TODO ^ uncomment to fix compilation |
33 | 38 | }
|
34 | 39 | }
|
35 | 40 | ```
|
36 | 41 |
|
37 | 42 | ### See also:
|
38 | 43 |
|
39 | 44 | [Tuples](../../primitives/tuples.md)
|
| 45 | +[Enums](../../custom_types/enum.md) |
0 commit comments