liveBook · Manning

Let else

As explained in Learn Rust in a Month of Lunches

let else is Rust binding syntax that requires a pattern match to succeed and requires the alternative branch to diverge when it fails.

let else is Rust syntax for matching a pattern and creating a variable that must be available afterward. When the pattern fails, the else block must end with diverging code, such as continue, break, or an early return. section 5.2.3

Skip missing values

Inside a loop, `let Some(number) = my_vec.get(index) else { continue; };` binds number when the vector lookup succeeds. A None skips to the next iteration; afterward, number is guaranteed to exist. section 5.2.3

fn main() {
    let my_vec = vec![2, 3, 4];
 
    for index in 0..10 {
        if let Some(number) = my_vec.get(index) {      #1
            println!("The number is: {number}");
        }
        let Some(number) = my_vec.get(index) else {    #2
        continue;
      };
        println!("The number is: {number}");
    }
}

Compare if let, which keeps number inside its block, with let else, which makes number available after the match and uses continue when matching fails. section 5.2.3

The else block may contain several statements, but it must finish by leaving the current control-flow path. This requirement guarantees that later code can use the bound variable safely. section 5.2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains syntax, scope, and diverging control flow through loop examples, without descending into compiler internals.
Examples
Uses vector lookups, Some and None, continue, break, and early return examples.
What it assumes
Builds from Option matching and if let, while defining diverging code with familiar break, continue, and return operations.
What you can do after
Apply let else in Rust loops to bind successful matches and handle failures with required early control flow.
How it connects
Connects pattern matching, Option, if let, variable scope, and diverging code.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.