Skip to content

Commit bb8b35a

Browse files
authored
Add a speaker note about trying to use a variable as a pattern (#2779)
1 parent bb1e1c9 commit bb8b35a

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/pattern-matching/match.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,21 @@ Key Points:
4747
result in other arms of the original `match` expression being considered.
4848
- The condition defined in the guard applies to every expression in a pattern
4949
with an `|`.
50+
- Note that you can't use an existing variable as the condition in a match arm,
51+
as it will instead be interpreted as a variable name pattern, which creates a
52+
new variable that will shadow the existing one. For example:
53+
```rust
54+
let expected = 5;
55+
match 123 {
56+
expected => println!("Expected value is 5, actual is {expected}"),
57+
_ => println!("Value was something else"),
58+
}
59+
```
60+
Here we're trying to match on the number 123, where we want the first case to
61+
check if the value is 5. The naive expectation is that the first case won't
62+
match because the value isn't 5, but instead this is interpreted as a variable
63+
pattern which always matches, meaning the first branch will always be taken.
64+
If a constant is used instead this will then work as expected.
5065

5166
# More To Explore
5267

0 commit comments

Comments
 (0)