Skip to content

Commit 0ef75a6

Browse files
committed
Document how the compiler disambiguates variable patterns from variant patterns
r=brson Closes #3851
1 parent decbbaa commit 0ef75a6

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

doc/rust.md

+15-3
Original file line numberDiff line numberDiff line change
@@ -2150,9 +2150,21 @@ match x {
21502150
~~~~
21512151

21522152
Records and structures can also be pattern-matched and their fields bound to variables.
2153-
When matching fields of a record, the fields being matched are specified
2154-
first, then a placeholder (`_`) represents the remaining fields.
2155-
2153+
When matching fields of a record,
2154+
the fields being matched are specified first,
2155+
then a placeholder (`_`) represents the remaining fields.
2156+
2157+
A pattern that's just a variable binding,
2158+
like `Nil` in the previous answer,
2159+
could either refer to an enum variant that's in scope,
2160+
or bind a new variable.
2161+
The compiler resolves this ambiguity by forbidding variable bindings that occur in ```match``` patterns from shadowing names of variants that are in scope.
2162+
For example, wherever ```List``` is in scope,
2163+
a ```match``` pattern would not be able to bind ```Nil``` as a new name.
2164+
The compiler interprets a variable pattern `x` as a binding _only_ if there is no variant named `x` in scope.
2165+
A convention you can use to avoid conflicts is simply to name variants with upper-case letters,
2166+
and local variables with lower-case letters.
2167+
21562168
~~~~
21572169
# type options = {choose: bool, size: ~str};
21582170
# type player = {player: ~str, stats: (), options: options};

0 commit comments

Comments
 (0)