if let

if let`if letallows you to combine` allows you to combine if`ifand` and let`let` together to reduce the overhead of certain kinds of pattern matches.

For example, let’s say we have some sort of Option<T>`Option. We want to call a function on it if it’s`. We want to call a function on it if it’s Some<T>`Some, but do nothing if it’s`, but do nothing if it’s None`None`. That looks like this:

fn main() { let option = Some(5); fn foo(x: i32) { } match option { Some(x) => { foo(x) }, None => {}, } }
match option {
    Some(x) => { foo(x) },
    None => {},
}

We don’t have to use match`matchhere, for example, we could use` here, for example, we could use if`if`:

fn main() { let option = Some(5); fn foo(x: i32) { } if option.is_some() { let x = option.unwrap(); foo(x); } }
if option.is_some() {
    let x = option.unwrap();
    foo(x);
}

Neither of these options is particularly appealing. We can use if let`if let` to do the same thing in a nicer way:

fn main() { let option = Some(5); fn foo(x: i32) { } if let Some(x) = option { foo(x); } }
if let Some(x) = option {
    foo(x);
}

If a pattern matches successfully, it binds any appropriate parts of the value to the identifiers in the pattern, then evaluates the expression. If the pattern doesn’t match, nothing happens.

If you’d rather to do something else when the pattern does not match, you can use else`else`:

fn main() { let option = Some(5); fn foo(x: i32) { } fn bar() { } if let Some(x) = option { foo(x); } else { bar(); } }
if let Some(x) = option {
    foo(x);
} else {
    bar();
}

while let`while let`

In a similar fashion, while let`while let` can be used when you want to conditionally loop as long as a value matches a certain pattern. It turns code like this:

fn main() { let option: Option<i32> = None; loop { match option { Some(x) => println!("{}", x), _ => break, } } }
loop {
    match option {
        Some(x) => println!("{}", x),
        _ => break,
    }
}

Into code like this:

fn main() { let option: Option<i32> = None; while let Some(x) = option { println!("{}", x); } }
while let Some(x) = option {
    println!("{}", x);
}