Skip to content

Commit

Permalink
Elaborate manual on matching (dereference patterns, lvalue/rvalue mat…
Browse files Browse the repository at this point in the history
…ching)

Signed-off-by: Edward Z. Yang <[email protected]>
  • Loading branch information
ezyang authored and adrientetar committed Jan 17, 2014
1 parent b2cac49 commit e33b1da
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions doc/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -2893,12 +2893,21 @@ tail value of `~Nil`. The second pattern matches _any_ list constructed with `Co
ignoring the values of its arguments. The difference between `_` and `*` is that the pattern `C(_)` is only type-correct if
`C` has exactly one argument, while the pattern `C(..)` is type-correct for any enum variant `C`, regardless of how many arguments `C` has.

To execute an `match` expression, first the head expression is evaluated, then
its value is sequentially compared to the patterns in the arms until a match
A `match` behaves differently depending on whether or not the head expression
is an [lvalue or an rvalue](#lvalues-rvalues-and-temporaries).
If the head expression is an rvalue, it is
first evaluated into a temporary location, and the resulting value
is sequentially compared to the patterns in the arms until a match
is found. The first arm with a matching pattern is chosen as the branch target
of the `match`, any variables bound by the pattern are assigned to local
variables in the arm's block, and control enters the block.

When the head expression is an lvalue, the match does not allocate a
temporary location (however, a by-value binding may copy or move from
the lvalue). When possible, it is preferable to match on lvalues, as the
lifetime of these matches inherits the lifetime of the lvalue, rather
than being restricted to the inside of the match.

An example of an `match` expression:

~~~~
Expand Down Expand Up @@ -2932,6 +2941,15 @@ This can be changed to bind to a reference by
using the ```ref``` keyword,
or to a mutable reference using ```ref mut```.

Patterns can also dereference pointers by using the ``&``,
``~`` or ``@`` symbols, as appropriate. For example, these two matches
on ``x: &int`` are equivalent:

~~~~
match *x { 0 => "zero", _ => "some" }
match x { &0 => "zero", _ => "some" }
~~~~

A pattern that's just an identifier,
like `Nil` in the previous answer,
could either refer to an enum variant that's in scope,
Expand Down

0 comments on commit e33b1da

Please sign in to comment.