1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-05 06:00:30 +02:00

Add a speaker note about trying to use a variable as a pattern (#2779)

This commit is contained in:
Nicole L
2025-06-18 17:05:32 -07:00
committed by GitHub
parent bb1e1c9414
commit bb8b35ab74

View File

@ -47,6 +47,21 @@ Key Points:
result in other arms of the original `match` expression being considered.
- The condition defined in the guard applies to every expression in a pattern
with an `|`.
- Note that you can't use an existing variable as the condition in a match arm,
as it will instead be interpreted as a variable name pattern, which creates a
new variable that will shadow the existing one. For example:
```rust
let expected = 5;
match 123 {
expected => println!("Expected value is 5, actual is {expected}"),
_ => println!("Value was something else"),
}
```
Here we're trying to match on the number 123, where we want the first case to
check if the value is 5. The naive expectation is that the first case won't
match because the value isn't 5, but instead this is interpreted as a variable
pattern which always matches, meaning the first branch will always be taken.
If a constant is used instead this will then work as expected.
# More To Explore