I have this piece of code:
fn main() {
let x = Some(1);
let y = Some(2);
println!("{}",matches!(x,y));
println!("{}",matches!(x,Some(2)));
}
that prints true and false
I would expect it to return false two time,because the values of Some are different. What is the reason behind this behaviour? Is y shadowed somehow under the hood?
>Solution :
What is the reason behind this behaviour? Is y shadowed somehow under the hood?
Yes, this introduces a new binding y which will match anything. This code produces warnings indicating that neither y is used:
warning: unused variable: `y`
--> src/main.rs:3:9
|
3 | let y = Some(2);
| ^ help: if this is intentional, prefix it with an underscore: `_y`
|
= note: `#[warn(unused_variables)]` on by default
warning: unused variable: `y`
--> src/main.rs:4:30
|
4 | println!("{}",matches!(x,y));
| ^ help: if this is intentional, prefix it with an underscore: `_y`
This is akin to Why is this match pattern unreachable when using non-literal patterns? but in a slightly different form. Here, matches!(x,y) is equivalent to this (see source for matches!):
match x {
y => true,
_ => false,
}
Identifiers are used to create new bindings in patterns (unless they are constants) and thus do not use the variable with that name.