Rust Reference ยท Patterns
@ bindings
Reference for Rust's @ pattern binding: giving a name to a value while also testing it against a range, enum variant or nested pattern, and the rules for Copy and moves.
The @ operator in a pattern, written name @ subpattern, tests the value against subpattern and, when it matches, also binds the whole matched value to name. It solves a common problem: a range or variant pattern checks a value but throws it away, and you still want to use it in the arm.
Without @ you would bind first and test later with a guard (n if (1..=9).contains(&n)). With @ the test lives in the pattern, so exhaustiveness checking still works.
match age { n @ 0..=17 => println!("minor, {n}"), n => println!("adult, {n}"), }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
name @ pattern n @ 1..=9 n @ (1 | 2 | 3) whole @ Enum::Variant { field: 0..=5, .. } Some(n @ 10..) rest @ .. // inside a slice pattern
| Part | Description |
|---|---|
name |
New binding for the whole value matched by pattern. It can be mut or ref. |
pattern |
Any pattern, including ranges, enum variants and slices. |
Errors and edge cases: an or-pattern after @ needs parentheses, as in n @ (1 | 2); writing n @ 1 | 2 means (n @ 1) | 2 and fails because the alternatives bind different names (E0408). Since Rust 1.56 you may also bind names inside the subpattern (whole @ Some(inner)), but both bindings must be Copy or references, because moving the same value twice is an error.
Usage notes
- Match against the same value twice.
whole @ Variant { field, .. }gives you the whole and a part; both bindings must not conflict (you cannot move the part out and keep using the whole). - Copy types are easy. For integers and
char,n @ 1..=9simply copies the number inton. - Ownership. Matching on an owned non-
Copyvalue moves it into the@binding. Match on a reference (match &msg) to keep the original, as in the second example. - Prefer it over guards for ranges. The compiler can prove
n @ 0..=9plusn @ 10..are exhaustive for unsigned types, but not guards. - Rest patterns. In slices,
tail @ ..binds the remaining elements as a subslice. See slice patterns. - Readability. If the name is only needed for printing, a short
@is clearer than a guard; for complex conditions, a guard is clearer.