Concise Control Flow with if-let

if let syntax allows to write if and let togather in a less verbose way to handle values that match one pattern while ignoring the rest.


let some_var = Some(0u8);
match some_var {
    Some(3) => println!("three"),
    _ => (),

can be written as:

if let Some(3) = some_var {

if let is a syntax sugar for match that runs code when the value matches one pattern and then ignores all other values.

An else block could as well be attached into if let. This else block would work like a wildcard, i.e._ in match can be replaced by else in if let.


let mut count = 0;
if let Coin::Quarter(state) = coin {
    println!("State quarter from {:?}!", state);
} else {
    count += 1;