File tree Expand file tree Collapse file tree 1 file changed +15
-0
lines changed Expand file tree Collapse file tree 1 file changed +15
-0
lines changed Original file line number Diff line number Diff line change @@ -47,6 +47,21 @@ Key Points:
47
47
result in other arms of the original ` match ` expression being considered.
48
48
- The condition defined in the guard applies to every expression in a pattern
49
49
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.
50
65
51
66
# More To Explore
52
67
You can’t perform that action at this time.
0 commit comments