46. Let Chains — Flatten Nested if-let with &&

Deeply nested if let blocks are one of Rust’s most familiar awkward moments. Rust 1.88 (2024 edition) finally fixes it: let chains let you &&-chain multiple let bindings and boolean guards in one if or while.

Before let chains, matching several optional values forced you to nest:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn describe(name: Option<&str>, age: Option<u32>) -> String {
    if let Some(n) = name {
        if let Some(a) = age {
            if a >= 18 {
                return format!("{n} is an adult");
            }
        }
    }
    "unknown".to_string()
}

Three levels of indentation just to check two Options and a condition. The actual logic is buried at the bottom.

With let chains, it collapses to a single if:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
fn describe(name: Option<&str>, age: Option<u32>) -> String {
    if let Some(n) = name
        && let Some(a) = age
        && a >= 18
    {
        format!("{n} is an adult")
    } else {
        "unknown".to_string()
    }
}

Bindings introduced in earlier lets are in scope for all subsequent conditions — n is available when checking a, and both are available in the body.

The same syntax works in while loops. This example processes tokens until it hits one it can’t parse:

1
2
3
4
5
6
7
8
9
let mut tokens = vec!["42", "17", "bad", "99"];
tokens.reverse(); // process front-to-back

while let Some(token) = tokens.pop()
    && let Ok(n) = token.parse::<i32>()
{
    println!("{n}");
}
// prints: 42, 17  — stops at "bad"

Short-circuit semantics apply: if any condition in the chain fails, Rust skips the rest and takes the else branch (or ends the while loop).

To enable let chains, set edition = "2024" in your Cargo.toml:

1
2
[package]
edition = "2024"

No unstable flags, no feature gates — it’s stable as of Rust 1.88 and available on the 2024 edition. If you’re still on 2021, this alone is a good reason to upgrade.

← Previous 45. get_disjoint_mut — Multiple Mutable References at Once Next → 47. Vec::pop_if — Conditionally Pop the Last Element