Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 996
LNK2005 Avatar asked Dec 12 '25 06:12

LNK2005


1 Answers

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);
}
like image 164
Masklinn Avatar answered Dec 15 '25 12:12

Masklinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!