Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust matches! macro different return value depending on if value is in variable or not

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading