diff --git a/src/flow_control/match/guard.md b/src/flow_control/match/guard.md index 9caa65aa00..6dba58f138 100644 --- a/src/flow_control/match/guard.md +++ b/src/flow_control/match/guard.md @@ -3,33 +3,38 @@ A `match` *guard* can be added to filter the arm. ```rust,editable +enum Temperature { + Celsius(i32), + Farenheit(i32), +} + fn main() { - let pair = (2, -2); - // TODO ^ Try different values for `pair` - - println!("Tell me about {:?}", pair); - match pair { - (x, y) if x == y => println!("These are twins"), - // The ^ `if condition` part is a guard - (x, y) if x + y == 0 => println!("Antimatter, kaboom!"), - (x, _) if x % 2 == 1 => println!("The first one is odd"), - _ => println!("No correlation..."), + 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 does not check arbitrary expressions for whether all -possible conditions have been checked. Therefore, you must use the `_` pattern -at the end. +Note that the compiler won't take guard conditions into account when checking +if all patterns are covered by the match expression. -```rust,editable +```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"), - _ => println!("Fell through"), // This should not be possible to reach + // _ => unreachable!("Should never happen."), + // TODO ^ uncomment to fix compilation } } ``` @@ -37,3 +42,4 @@ fn main() { ### See also: [Tuples](../../primitives/tuples.md) +[Enums](../../custom_types/enum.md)