mirror of
https://github.com/rust-lang/rust.git
synced 2025-01-10 06:47:34 +00:00
Add '@' subpattern binding and examples to manual and tutorial
This commit is contained in:
parent
2c5b04cef1
commit
7b1d124f6e
21
doc/rust.md
21
doc/rust.md
@ -2939,6 +2939,27 @@ This can be changed to bind to a reference by
|
||||
using the `ref` keyword,
|
||||
or to a mutable reference using `ref mut`.
|
||||
|
||||
Subpatterns can also be bound to variables by the use of the syntax
|
||||
`variable @ pattern`.
|
||||
For example:
|
||||
|
||||
~~~~
|
||||
enum List { Nil, Cons(uint, ~List) }
|
||||
|
||||
fn is_sorted(list: &List) -> bool {
|
||||
match *list {
|
||||
Nil | Cons(_, ~Nil) => true,
|
||||
Cons(x, ref r @ ~Cons(y, _)) => (x <= y) && is_sorted(*r)
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a = Cons(6, ~Cons(7, ~Cons(42, ~Nil)));
|
||||
assert!(is_sorted(&a));
|
||||
}
|
||||
|
||||
~~~~
|
||||
|
||||
Patterns can also dereference pointers by using the `&`,
|
||||
`~` or `@` symbols, as appropriate. For example, these two matches
|
||||
on `x: &int` are equivalent:
|
||||
|
@ -520,6 +520,16 @@ to the value of the matched value inside of the arm's action. Thus, `(0.0,
|
||||
y)` matches any tuple whose first element is zero, and binds `y` to
|
||||
the second element. `(x, y)` matches any two-element tuple, and binds both
|
||||
elements to variables.
|
||||
A subpattern can also be bound to a variable, using `variable @ pattern`. For
|
||||
example:
|
||||
|
||||
~~~~
|
||||
# let age = 23;
|
||||
match age {
|
||||
a @ 0..20 => println!("{} years old", a),
|
||||
_ => println!("older than 21")
|
||||
}
|
||||
~~~~
|
||||
|
||||
Any `match` arm can have a guard clause (written `if EXPR`), called a
|
||||
*pattern guard*, which is an expression of type `bool` that
|
||||
|
Loading…
Reference in New Issue
Block a user