Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make guard examples clearer around _ #1550

Merged
merged 4 commits into from
Jun 9, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions src/flow_control/match/guard.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,37 +3,43 @@
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
}
}
```

### See also:

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