21.9 Variable Bindings With @

The @ syntax lets you bind a value to a variable name while still applying further pattern checks. For instance, you can match numbers within a range while also capturing the matched 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);
}

Here, n @ 1..=3 matches numbers in the inclusive range 1 through 3 and binds them to n.

21.9.1 Example With Option<u32> and a Specific Value

You can also use @ to match a literal while binding that same literal:

fn some_number() -> Option<u32> {
    Some(42)
}

fn main() {
    match some_number() {
        Some(n @ 42) => println!("The Answer: {}!", n),
        Some(n) => println!("Not interesting... {}", n),
        None => (),
    }
}

Some(n @ 42) matches only if the Option contains 42, capturing it in n. If it holds anything else, the next arm (Some(n)) applies.