More Control Flow

There are a couple of control flow constructs we skipped over earlier, because they rely on some concepts we didn't have. Namely, you can combine pattern matching with if and while. This comes in really handy when you want to do something only for a particular variant.

Here's a contrived example of retrieving something from a map, and doing something different in each case.

#![allow(unused)]
fn main() {
// let's just pretend we got this from a map, okay?
let value = Some(42);

if let Some(inner) = value {
    println!("inner was {inner}");
} else {
    println!("this is the failure case!");
}
}

The general setup is that you put a variant on the left hand side inside an if let, and if the match can be satisfied (if it works), then it'll fill in the placeholder variables. If that match doesn't succeed, then you fall through to the else case.

The same thing works in loops. One common use is with iterators, but you can use it with any enum. (I see this used a lot less than if let.)

#![allow(unused)]
fn main() {
let values = vec![1, 2, 3, 4, 5];
let mut iter = values.iter();

while let Some(v) = iter.next() {
    println!("v = {v}");
}
}