1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-08-08 16:26:35 +02:00

Clarify Matching Values section (#2833)

This commit is contained in:
Vinh Tran
2025-07-29 22:09:51 -04:00
committed by GitHub
parent a0edd51120
commit 16d25dbed7

View File

@ -41,10 +41,24 @@ Key Points:
- Match guards as a separate syntax feature are important and necessary when we - Match guards as a separate syntax feature are important and necessary when we
wish to concisely express more complex ideas than patterns alone would allow. wish to concisely express more complex ideas than patterns alone would allow.
- They are not the same as separate `if` expression inside of the match arm. An - Match guards are different from `if` expressions after the `=>`. An `if`
`if` expression inside of the branch block (after `=>`) happens after the expression is evaluated after the match arm is selected. Failing the `if`
match arm is selected. Failing the `if` condition inside of that block will condition inside of that block won't result in other arms of the original
result in other arms of the original `match` expression being considered. `match` expression being considered. In the following example, the wildcard
pattern `_ =>` is never even attempted.
```rust,editable
#[rustfmt::skip]
fn main() {
let input = 'a';
match input {
key if key.is_uppercase() => println!("Uppercase"),
key => if input == 'q' { println!("Quitting") },
_ => println!("Bug: this is never printed"),
}
}
```
- The condition defined in the guard applies to every expression in a pattern - The condition defined in the guard applies to every expression in a pattern
with an `|`. with an `|`.
- Note that you can't use an existing variable as the condition in a match arm, - Note that you can't use an existing variable as the condition in a match arm,