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:
| |
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:
| |
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:
| |
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:
| |
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.