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

Time:01-02

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?

CodePudding user response:

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.

CodePudding user response:

Well the example isn't very good. But consider this:

fn foo(o: Option<i32>) {
    if let Some(n) = o {
        println!("{n}");
    }
}

Which prints the value inside the option only if it is Some(...).

if let is a shortand version of match if you're only interested in one specific case.

Also note that == can only be used with types implementing PartialEq, while if let works with any type you can pattern match on.

CodePudding user response:

Another advantage of if let besides what mentioned in the other answers is that not always you can use ==. There are types that do not support comparisons (they do not implement PartialEq) for various possible reasons (the author of the library didn't think about it/the types contain some structs that doesn't support comparisons/comparisons don't make sense for those types). In those cases, you cannot use ==, but you still can use if let.

  • Related