Questions about the examples of match guards in the ch18-03-pattern-syntax section

Matching Named Variables mentions:

... However, there is a complication when you use named variables in match expressions. Because match starts a new scope, variables declared as part of a pattern inside the match expression will shadow those with the same name outside the match construct, as is the case with all variables. ...

.... Because we’re in a new scope inside the match expression, this is a new y variable, not the y we declared at the beginning with the value 10. This new y binding will match any value inside a Some , which is what we have in x . Therefore, this new y binds to the inner value of the Some in x . ...

To create a match expression that compares the values of the outer x and y , rather than introducing a shadowed variable, we would need to use a match guard conditional instead. We’ll talk about match guards later in the “Extra Conditionals with Match Guards” section.

Especially this one:

To create a match expression that compares the values of the outer x and y , rather than introducing a shadowed variable, we would need to use a match guard conditional instead

If you just want to compare x and y, rather than introducing a shadowed variable, wouldn't it be fine to not use parameters with the same name?

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

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

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

Yes.

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.