diff options
| author | Edward Z. Yang <ezyang@cs.stanford.edu> | 2013-12-09 22:14:43 -0800 |
|---|---|---|
| committer | Adrien Tétar <adri-from-59@hotmail.fr> | 2014-01-17 19:44:51 +0100 |
| commit | e33b1dabd35685e586f85f3e53783e31871bc5b7 (patch) | |
| tree | 6ff11f750ff264c54cc8c25f3cf04d1909bd9e85 | |
| parent | b2cac497e8989fb6d26c1f20441e8354950bbcc3 (diff) | |
| download | rust-e33b1dabd35685e586f85f3e53783e31871bc5b7.tar.gz rust-e33b1dabd35685e586f85f3e53783e31871bc5b7.zip | |
Elaborate manual on matching (dereference patterns, lvalue/rvalue matching)
Signed-off-by: Edward Z. Yang <ezyang@cs.stanford.edu>
| -rw-r--r-- | doc/rust.md | 22 |
1 files changed, 20 insertions, 2 deletions
diff --git a/doc/rust.md b/doc/rust.md index ad93964d6aa..f955cbda9b8 100644 --- a/doc/rust.md +++ b/doc/rust.md @@ -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: ~~~~ @@ -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, |
