LNK2005
LNK2005

Reputation: 163

What's the main difference between match and if-let in rust?

I get little confused when learning about control flow. I don't understand the difference between if-let and match.

fn main() {
    let some_u8_value = Some(8u8);
    // println!(" {} ", some_u8_value);
    if let Some(value) = some_u8_value {
        println!(" {} ", value);
    } else {
        println!("not a num");
    }

    match some_u8_value {
        Some(value) => println!(" {} ", value),
        None => println!("not a num"),
    }
}

Why do we need if-let?

Upvotes: 15

Views: 6871

Answers (1)

Masklinn
Masklinn

Reputation: 42302

Why do we need if-let?

We don't need it, it's a convenience feature. Per RFC 160 which introduced it:

[if let] allows for refutable pattern matching without the syntactic and semantic overhead of a full match, and without the corresponding extra rightward drift.

and

The idiomatic solution today for testing and unwrapping an Option looks like

match optVal {
    Some(x) => {
        doSomethingWith(x);
    }
    None => {}
}

This is unnecessarily verbose, with the None => {} (or _ => {}) case being required, and introduces unnecessary rightward drift (this introduces two levels of indentation where a normal conditional would introduce one).

[explanation of the issues with using a simple if with is_some and unwrap]

The if let construct solves all of these problems, and looks like this:

if let Some(x) = optVal {
    doSomethingWith(x);
}

Upvotes: 32

Related Questions