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

Is `if let` just another way of writing other `if` statements?

So I’m learning Rust and I’m learning about pattern matching and "if let" statements as alternatives to matching expressions. I was watching this video regarding "if let" which is mentioned at 11:00 and they give this example:

fn main() { 
     let some_value: Option<i32> = Some(3);
    
     if let Some(3) = some_value {
          println!("three");
     }
}

I get that this is useful if you only have one specific pattern you want to match and the matching expression is too verbose, but if this is the case, couldn’t you simply do this?:

fn main() {
    let some_value: Option<i32> = Some(3);
    if some_value == Some(3) {
        println!("three");
    }
}

Is there something about this expression that is inferior to the "if let" statement that I’m not aware of?

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 :

The if let form lets you be more generic than your example. You can’t do if some_value == Some(n) unless n is defined, but you can do:

if let Some(n) = some_value { ... }

Where that now gives you an n you can work with.

I think you’ll find as you work with Rust more that the match form Some(n) shows up a lot more often than Some(1) for some specific value.

Don’t forget you can also do this:

if let Some(1) | Some(2) = some_value { ... }

Where that’s a lot more thorny with a regular if unless you’re using matching like this:

if matches!(some_value, Some(1) | Some(2)) { ... }

So there’s a number of useful options here that might fit better in some situations.

Don’t forget about cargo clippy which will point out if there’s better ways of expressing something.

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