Why "accessing a variable makes it impossible to branch"?

Newbie here.

Reading a chapter on binding in "Rust by Example", I am not following this statement: "Indirectly accessing a variable makes it impossible to branch and use that variable without re-binding.".

I've tweaked the example to use guards instead of the @ sigil, and it still works for various ages:

fn main() {
    println!("Tell me what type of person you are");

    match age() {
        0             => println!("I haven't celebrated my first birthday yet"),
        // Could `match` 1 ..= 12 directly but then what age
        // would the child be? Instead, bind to `n` for the
        // sequence of 1 ..= 12. Now the age can be reported.
        n if n >= 1  && n <= 12 => println!("I'm a child of age {:?}", n),
        n if n >= 13  && n <= 19 => println!("I'm a teen of age {:?}", n),
        // Nothing bound. Return the result.
        n             => println!("I'm an old person of age {:?}", n),
    }
}

What am I missing? Can someone please provide an example to demonstrate this "makes it impossible to branch" thing? TIA!

I mean you still are binding to n, whether you are using the @ or not.

Indirectly accessing a variable makes it impossible to branch and use that variable without re-binding.

That's just a poorly worded statement. I'm not sure how to word it better, but the point is that you need to bind the value to a name to use it. In your example you have explicitly bound the value as n in each branch, with the if guards asserting the required conditions. But let's say you just use a pattern:

    match age() {
        0             => println!("I haven't celebrated my first birthday yet"),
        // Could `match` 1 ..= 12 directly but then what age
        // would the child be? Instead, bind to `n` for the
        // sequence of 1 ..= 12. Now the age can be reported.
        1  ..= 12 => ???,
        13 ..= 19 => ???,
        // Nothing bound. Return the result.
        n             => println!("I'm an old person of age {:?}", n),
    }

How would you access the value of age() in the second and third branch? You can't. You need to either bind age() to a local variable: let my_age = age(); match my_age { ... }, or you need to introduce a new pattern which binds that value.

It's a trivial thing, really. They just want to provide some motivation for the ident @ pat syntax.

1 Like

Makes sense. Thanks a bunch. Should we make this chapter easier to grok?

If you have time to spare, definitely!

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.