]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/flow_control/match/guard.md
New upstream version 1.63.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / flow_control / match / guard.md
CommitLineData
2c00a5a8
XL
1# Guards
2
3A `match` *guard* can be added to filter the arm.
4
5```rust,editable
923072b8
FG
6enum Temperature {
7 Celsius(i32),
8 Farenheit(i32),
9}
10
2c00a5a8 11fn main() {
923072b8
FG
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),
2c00a5a8
XL
22 }
23}
24```
25
923072b8
FG
26Note that the compiler won't take guard conditions into account when checking
27if all patterns are covered by the match expression.
5869c6ff 28
923072b8 29```rust,editable,ignore,mdbook-runnable
5869c6ff
XL
30fn main() {
31 let number: u8 = 4;
32
33 match number {
34 i if i == 0 => println!("Zero"),
35 i if i > 0 => println!("Greater than zero"),
923072b8
FG
36 // _ => unreachable!("Should never happen."),
37 // TODO ^ uncomment to fix compilation
5869c6ff
XL
38 }
39}
40```
41
2c00a5a8
XL
42### See also:
43
dc9dc135 44[Tuples](../../primitives/tuples.md)
923072b8 45[Enums](../../custom_types/enum.md)