'Any other reason why we use if-let rather than if in Rust?

I don't see the reason why we use if let and just usual if. In Rust book, chapter 6.3, the sample code is below:

let some_u8_value = Some(0u8);
if let Some(3) = some_u8_value {
    println!("three");
}

The code above is same with:

let some_u8_value = Some(0u8);
if Some(3) == some_u8_value {
    println!("three");
}

Any other reason on why we would use if let or what is it specifically for?



Solution 1:[1]

Another reason is if you wish to use the pattern bindings. For example consider an enum:

enum Choices {
  A,
  B,
  C(i32),
}

If you wish to implement specific logic for the C variant of Choices, you can use the if-let expression:

let choices: Choices = ...;

if let Choices::C(value) = choices {
    println!("{}", value * 2);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1