You've already forked comprehensive-rust
mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-07-05 14:10:29 +02:00
Add a speaker note about trying to use a variable as a pattern (#2779)
This commit is contained in:
@ -47,6 +47,21 @@ Key Points:
|
|||||||
result in other arms of the original `match` expression being considered.
|
result in other arms of the original `match` expression being considered.
|
||||||
- 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,
|
||||||
|
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
|
# More To Explore
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user