Search code examples
rust

Rust: What does the `@` (at sign) operator do?


I saw the following line in my code, and I am not sure what it does as I haven't encountered the @ operator before.

if let e@Err(_) = changed {
    ...
}

Can this line be written without the @ operator, what would that look like?


Solution

  • It's a way to bind the matched value of a pattern to a variable(using the syntax: variable @ subpattern).

    Example:

    let x = 2;
    
    match x {
        e @ 1 ..= 5 => println!("got a range element {}", e),
        _ => println!("anything"),
    }