Sub topic 3
Let Chains: Patterns and Conditions with `&&`
Assume you know Option, Result, match, and basic ownership. A let chain combines pattern matching and boolean conditions in one if or while condition. Each link must succeed before the next link runs.
fn describe(first: Option<&str>) -> String {
if let Some(text) = first
&& let Ok(number) = text.parse::<i32>()
&& number > 0
{
format!("positive number {number}")
} else {
String::from("no positive number")
}
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("-1")));
println!("{}", describe(None));
}The links run from left to right. The text binding is available to the next link, and number is available in the final condition and the body.
Which Rust version and edition you need
Let chains require Rust 1.88 or newer. Use the 2024 edition in Cargo.toml:
[package]
name = "let-chain-demo"
version = "0.1.0"
edition = "2024"The && operator means every link must be true. A failed pattern or boolean condition skips the body and selects else, if present.
Temporaries and scope in edition 2024
Edition 2024 shortens the temporary scope of an if let condition. Temporary values created while evaluating the condition are dropped after the condition finishes, before the body runs. This reduces accidental lock or resource lifetimes.
If the body needs a value, bind it before the if let, or create an owned value whose lifetime is clear. Do not depend on a temporary remaining alive throughout the whole if statement.
Choosing the construct
| Construct | Best use |
|---|---|
| `match` | Handle several meaningful patterns |
| `if let` | Handle one interesting pattern |
| `let else` | Bind a required value or exit early |
| Let chain | Combine pattern checks and conditions |
| `matches!` | Ask whether a pattern matches, returning `bool` |
Exercise
Rewrite if let Some(n) = value { if n > 10 { ... } } as a let chain.
Show answer
if let Some(n) = value && n > 10 { ... }