21.9 Variable Bindings With @
The @
syntax allows you to bind a matched value to a variable name while still adding constraints. For instance, you can match integers in a specific range while capturing the value:
fn check_number(num: i32) { match num { n @ 1..=3 => println!("Small number: {}", n), n @ 4..=10 => println!("Medium number: {}", n), other => println!("Out of range: {}", other), } } fn main() { check_number(2); check_number(7); check_number(20); }
n @ 1..=3
matches numbers in the inclusive range 1 to 3 and makes the matched number available as n
.
21.9.1 Example With Option<u32>
and a Specific Value
You can also use the @
binding syntax to match a specific value within an enum variant:
fn some_number() -> Option<u32> { Some(42) } fn main() { match some_number() { // Got `Some` variant, match if its value (bound to `n`) is 42 Some(n @ 42) => println!("The Answer: {}!", n), // Match any other number Some(n) => println!("Not interesting... {}", n), // Match anything else (`None`) _ => (), } }
Here, Some(n @ 42)
matches the Some
variant only if the contained value is exactly 42
, and captures it as n
. If the value in Some
is anything else, it falls through to the next arm. This technique lets you match a specific literal while still naming it in that pattern’s body.