Skip to content

Commit ea72a40

Browse files
authored
Merge pull request #1550 from xiaochuanyu/guard-example-clearer
Make guard examples clearer around `_` closes #1539
2 parents dbb7e5e + 8cbf809 commit ea72a40

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/flow_control/match/guard.md

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,43 @@
33
A `match` *guard* can be added to filter the arm.
44

55
```rust,editable
6+
enum Temperature {
7+
Celsius(i32),
8+
Farenheit(i32),
9+
}
10+
611
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),
1722
}
1823
}
1924
```
2025

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.
2428

25-
```rust,editable
29+
```rust,editable,ignore,mdbook-runnable
2630
fn main() {
2731
let number: u8 = 4;
2832
2933
match number {
3034
i if i == 0 => println!("Zero"),
3135
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
3338
}
3439
}
3540
```
3641

3742
### See also:
3843

3944
[Tuples](../../primitives/tuples.md)
45+
[Enums](../../custom_types/enum.md)

0 commit comments

Comments
 (0)