3

I'm reading the Rust by Example page on Binding in match statements and this sentence is confusing me, "Indirectly accessing a variable makes it impossible to branch and use that variable without re-binding."

I think I understand when it goes on to say, "match provides the @ sigil for binding values to names" since I can understand practically how the n @ 13 ..= 19 works in that example match statement. There are a range of values that we're matching on, and if we want to access the specific value in the range, then we need to bind it to a variable.

However, the first sentence is confusing me on multiple points and I feel like I might be missing something important that could trip me up later.

  1. What does it mean that we're indirectly accessing a variable?
  2. What variable, the n?
  3. Why does indirectly accessing the variable make it "impossible to branch and use that variable without re-binding"?
  4. In what way are we re-binding? By using @?
  5. I saw another question on SO where the @ sigil was used in a if let e@Err(_) = changed ... so I am also confused why the second sentence says that match provides the @ sigil (it seems like a more general language feature that can be used elsewhere). What is the general purpose of the @ sigil?

My understanding of binding is that we have a value like 10 that we can bind to a variable like x. I only know about binding in the form let x = *thing*; though. The whole purpose of the @ sigil is not clear to me. I've tried searching the Rust docs for more info about @ and didn't get anything.

Rust by Example code:

fn age() -> u32 {
    15
}

fn main() {
    match age() {
        0             => println!("I haven't celebrated my first birthday yet"),
        n @ 1  ..= 12 => println!("I'm a child of age {:?}", n),
        n @ 13 ..= 19 => println!("I'm a teen of age {:?}", n),
        n             => println!("I'm an old person of age {:?}", n),
    }
}
1
  • 1
    The purpose of @ is to allow you to both pattern-match a value and use that value at the same time. It is provided by match but that doesn't mean that it isn't also provided by other pattern-matching mechanisms, such as if let.
    – cdhowie
    Commented Aug 9, 2022 at 20:51

0

Browse other questions tagged or ask your own question.