Skip to content

Commit 03d9d62

Browse files
committed
Discuss (*) patterns in reference documentation
1 parent ea3362d commit 03d9d62

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

doc/rust.md

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2155,10 +2155,30 @@ alt_pat : pat [ "to" pat ] ? [ "if" expr ] ;
21552155
An `alt` expression branches on a *pattern*. The exact form of matching that
21562156
occurs depends on the pattern. Patterns consist of some combination of
21572157
literals, destructured enum constructors, records and tuples, variable binding
2158-
specifications and placeholders (`_`). An `alt` expression has a *head
2158+
specifications, wildcards (`*`), and placeholders (`_`). An `alt` expression has a *head
21592159
expression*, which is the value to compare to the patterns. The type of the
21602160
patterns must equal the type of the head expression.
21612161

2162+
In a pattern whose head expression has an `enum` type, a placeholder (`_`) stands for a
2163+
*single* data field, whereas a wildcard `*` stands for *all* the fields of a particular
2164+
variant. For example:
2165+
2166+
~~~~
2167+
enum list<X> { nil, cons(X, @list<X>) }
2168+
2169+
let x: list<int> = cons(10, @cons(11, @nil));
2170+
2171+
alt x {
2172+
cons(_, @nil) { fail "singleton list"; }
2173+
cons(*) { ret; }
2174+
nil { fail "empty list"; }
2175+
}
2176+
~~~~
2177+
2178+
The first pattern matches lists constructed by applying `cons` to any head value, and a
2179+
tail value of `@nil`. The second pattern matches `any` list constructed with `cons`,
2180+
ignoring the values of its arguments.
2181+
21622182
To execute an `alt` expression, first the head expression is evaluated, then
21632183
its value is sequentially compared to the patterns in the arms until a match
21642184
is found. The first arm with a matching pattern is chosen as the branch target

0 commit comments

Comments
 (0)