Matching Named Variables mentions:
... However, there is a complication when you use named variables in
match
expressions. Becausematch
starts a new scope, variables declared as part of a pattern inside thematch
expression will shadow those with the same name outside thematch
construct, as is the case with all variables. ....... Because we’re in a new scope inside the
match
expression, this is a newy
variable, not they
we declared at the beginning with the value 10. This newy
binding will match any value inside aSome
, which is what we have inx
. Therefore, this newy
binds to the inner value of theSome
inx
. ...To create a
match
expression that compares the values of the outerx
andy
, 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 outerx
andy
, 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);
}