What is the difference between if and if let?

what is the difference between if and if let?
Can I change the code below:

let some_u8_value = Some(0u8);
if let Some(3) = some_u8_value {
    println!("doesn't match!");


let some_u8_value = Some(0u8);
if  Some(3) == some_u8_value {
    println!("doesn't match!");

if let is for putting definition expressions in your logic.

So, it's the same as a let, but as an expression with if in front of it. It's commonly used for testing if a value is as expected or can be set, like when returning a value from a function. I can't help much beyond that since I don't understand Rust enough yet to know specifically when it would be used.


Concise Control Flow with if let - The Rust Programming Language - it's shorthand for a simple match statement. An if condition and (optional) assignment in one expression, hence the name.

In the example you gave, there's no need for if let because you're not pattern matching on the option but simply doing an equality check.

1 Like

You can extract nested values with an if let. The intended use case of if let is more like

if let Some(aaaaa) = some_u8_value {
    println!("inner value: {}", aaaaa);

instead of

if let Some(3) = some_u8_value {

In your example, it makes no difference, but I find the second version with == more ideomatic.


Also, if let works even if the type doesn't implement PartialEq. E.g.

struct S(i32); // note, no #[derive(PartialEq)]

let s = S(5);
if let S(5) = s { /* works */ }
if s == S(5) { /* doesn't */ }

My understanding is that

if + bool condition
if let + pattern matching

This topic was automatically closed after 25 days. New replies are no longer allowed.