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.
- What does it mean that we're indirectly accessing a variable?
- What variable, the
n
? - Why does indirectly accessing the variable make it "impossible to branch and use that variable without re-binding"?
- In what way are we re-binding? By using @?
- 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),
}
}
@
is to allow you to both pattern-match a value and use that value at the same time. It is provided bymatch
but that doesn't mean that it isn't also provided by other pattern-matching mechanisms, such asif let
.