cognitive-engineering-lab / rust-book

The Rust Programming Language: Experimental Edition
https://rust-book.cs.brown.edu
Other
506 stars 82 forks source link

Presenting shadowing as a problem in the context of match guards is confusing #68

Open seishun opened 1 year ago

seishun commented 1 year ago

URL to the section(s) of the book with this problem: https://rust-book.cs.brown.edu/ch18-03-pattern-syntax.html#extra-conditionals-with-match-guards

Description of the problem:

In Listing 18-11, we mentioned that we could use match guards to solve our pattern-shadowing problem. Recall that we created a new variable inside the pattern in the match expression instead of using the variable outside the match. That new variable meant we couldn’t test against the value of the outer variable. Listing 18-27 shows how we can use a match guard to fix this problem.

But using a match guard doesn't fix this problem, using another name (n) does - and it would even without a match guard, for example:

fn main() {
    let x = Some(5);
    let y = 10;

    match x {
        Some(50) => println!("Got 50"),
        Some(n) => {
            if n == y {
                println!("Matched, n = {}", n);
            } else {
                println!("Default case, x = {:?}", x);
            }
        },
        _ => println!("Default case, x = {:?}", x),
    }

    println!("at the end: x = {:?}, y = {}", x, y);
}

Suggested fix:

Remove the implication that shadowing is the problem that using a match guard solves.