Skip to content

Commit 7b1d124

Browse files
committed
Add '@' subpattern binding and examples to manual and tutorial
1 parent 2c5b04c commit 7b1d124

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

doc/rust.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2939,6 +2939,27 @@ This can be changed to bind to a reference by
29392939
using the `ref` keyword,
29402940
or to a mutable reference using `ref mut`.
29412941

2942+
Subpatterns can also be bound to variables by the use of the syntax
2943+
`variable @ pattern`.
2944+
For example:
2945+
2946+
~~~~
2947+
enum List { Nil, Cons(uint, ~List) }
2948+
2949+
fn is_sorted(list: &List) -> bool {
2950+
match *list {
2951+
Nil | Cons(_, ~Nil) => true,
2952+
Cons(x, ref r @ ~Cons(y, _)) => (x <= y) && is_sorted(*r)
2953+
}
2954+
}
2955+
2956+
fn main() {
2957+
let a = Cons(6, ~Cons(7, ~Cons(42, ~Nil)));
2958+
assert!(is_sorted(&a));
2959+
}
2960+
2961+
~~~~
2962+
29422963
Patterns can also dereference pointers by using the `&`,
29432964
`~` or `@` symbols, as appropriate. For example, these two matches
29442965
on `x: &int` are equivalent:

doc/tutorial.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,16 @@ to the value of the matched value inside of the arm's action. Thus, `(0.0,
520520
y)` matches any tuple whose first element is zero, and binds `y` to
521521
the second element. `(x, y)` matches any two-element tuple, and binds both
522522
elements to variables.
523+
A subpattern can also be bound to a variable, using `variable @ pattern`. For
524+
example:
525+
526+
~~~~
527+
# let age = 23;
528+
match age {
529+
a @ 0..20 => println!("{} years old", a),
530+
_ => println!("older than 21")
531+
}
532+
~~~~
523533

524534
Any `match` arm can have a guard clause (written `if EXPR`), called a
525535
*pattern guard*, which is an expression of type `bool` that

0 commit comments

Comments
 (0)