Sub topic 10
let chains: patterns and conditions with &&
This chapter assumes you know match, Option and Result, if let, while let, and let else. It also assumes you know what refutable patterns are, and that you have seen the nesting that appears when several if let blocks depend on one another. A let chain removes that nesting. It joins pattern matches and boolean tests in a single condition.
The problem a let chain solves
Suppose you need three things to hold at once. An optional string must exist, it must parse as an integer, and the integer must be positive. Without let chains, each dependent step opens a new block:
fn describe(first: Option<&str>) -> String {
if let Some(text) = first {
if let Ok(n) = text.parse::<i32>() {
if n > 0 {
return format!("positive number {n}");
}
}
}
String::from("no positive number")
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("-1")));
println!("{}", describe(None));
}Every step pushes the real work one level to the right. The fallback also sits far from the checks it belongs to. You cannot merge the blocks with &&, because if let Some(text) = first && ... was a syntax error before let chains.
The let chain form
A let chain is a condition made of one or more links joined by &&. Each link is either a let pattern match or an ordinary boolean expression. The same function becomes:
// Requires Rust 1.88 or newer and edition = "2024" in Cargo.toml.
fn describe(first: Option<&str>) -> String {
if let Some(text) = first
&& let Ok(n) = text.parse::<i32>()
&& n > 0
{
format!("positive number {n}")
} else {
String::from("no positive number")
}
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("-1")));
println!("{}", describe(None));
}Three rules explain how this works.
- Left to right. Links run in the order you write them. The chain stops at the first link that fails.
- Bindings flow forward. A name bound by an earlier
letlink is visible in every later link and in the success block. Heretextis used by the second link, andnis used by the third link and byformat!. - One else for the whole chain. If any link fails, control goes to the single
elsebranch, or theifproduces()when there is noelse. Names bound in the chain are not available inelse, because the chain may have stopped before binding them.
The layout above is the convention rustfmt produces. Each link goes on its own line, and the opening brace sits on its own line when the condition spans several lines.
How evaluation proceeds
Because && short-circuits, a failed link means later links never run. That matters when a later link has a side effect or is expensive:
fn check(label: &str, result: bool) -> bool {
println!("checking {label}");
result
}
fn main() {
if check("a", true)
&& let Some(x) = Some(1)
&& check("b", false)
&& check("c", true)
{
println!("all passed, x = {x}");
} else {
println!("chain failed");
}
}This prints checking a, checking b, and chain failed. The call check("c", true) never happens. The example also shows that boolean links and let links can appear in any order.
Using let chains in practice
Dependent lookups
The most common use is a lookup, then a conversion, then a validation:
use std::collections::HashMap;
fn timeout_ms(config: &HashMap<String, String>) -> u64 {
if let Some(raw) = config.get("timeout")
&& let Ok(secs) = raw.trim().parse::<u64>()
&& secs > 0
{
secs * 1000
} else {
5000
}
}
fn main() {
let mut config = HashMap::new();
println!("{}", timeout_ms(&config));
config.insert("timeout".to_string(), " 3 ".to_string());
println!("{}", timeout_ms(&config));
config.insert("timeout".to_string(), "0".to_string());
println!("{}", timeout_ms(&config));
}The output is 5000, 3000, and 5000. A missing key, an unparsable value, and a zero all fall to the same default, so the policy is written once.
Borrowing through the chain
Links can borrow from earlier bindings. Matching on a reference avoids moving a field out of a struct:
struct User {
name: Option<String>,
age: Option<u8>,
}
fn greeting(user: &User) -> String {
if let Some(name) = &user.name
&& let Some(age) = user.age
&& age >= 18
{
format!("Welcome, {name}")
} else {
String::from("Welcome, guest")
}
}
fn main() {
let adult = User { name: Some("Ana".into()), age: Some(30) };
let minor = User { name: Some("Bo".into()), age: Some(12) };
println!("{}", greeting(&adult));
println!("{}", greeting(&minor));
}Here name is a &String that borrows from user. The age field is Option<u8>, which is Copy, so matching it by value is fine. The rules are the same as for a single if let. A pattern that binds by value moves non-Copy data out of the scrutinee, so match on a reference when you need the original afterward.
else if let chains
A chain can also appear after else, and you can mix chains with single-pattern checks:
fn classify(a: Option<i32>, b: Option<i32>) -> &'static str {
if let Some(x) = a
&& let Some(y) = b
&& x == y
{
"equal pair"
} else if let Some(x) = a
&& x < 0
{
"negative first"
} else {
"other"
}
}
fn main() {
println!("{}", classify(Some(2), Some(2)));
println!("{}", classify(Some(-5), None));
println!("{}", classify(None, None));
}Each else if starts its own chain. Bindings from the first chain are not visible in the second.
while let chains
The same syntax works in while. The loop continues only while every link holds:
fn main() {
let mut queue = vec![3, 8, -1, 5];
while let Some(item) = queue.pop()
&& item >= 0
{
println!("processing {item}");
}
println!("left in queue: {queue:?}");
}The output is processing 5, then left in queue: [3, 8]. The -1 is popped, fails the item >= 0 test, and ends the loop. It is not put back. If you need to stop without consuming the element, use peek, last, or an index in the condition instead.
What a let chain cannot do
| Attempt | Result | Column | Column |
|---|---|---|---|
| `if let Some(x) = a \ | \ | let Some(x) = b` | Error. Only `&&` joins links. |
| `if (let Some(x) = a) && x > 0` | Error. A `let` link cannot be wrapped in parentheses. | ||
| `let ok = a.is_some() && let Some(x) = a;` | Error. `let` links are allowed only in `if` and `while` conditions. | ||
| Using `x` in the `else` block | Error. The chain may have stopped before `x` was bound. | ||
| Chain in an edition 2021 crate | Error saying let chains need edition 2024. |
For an "either pattern" test, use an or-pattern inside one let, such as if let Some(1 | 2) = n. For more complex alternatives, use match.
Version and edition requirements
Let chains were stabilized in Rust 1.88, and they are available only in crates that use edition 2024. The restriction exists because edition 2024 also changed how temporaries in if let are dropped, and let chains depend on that change. A project needs both of these:
[package]
name = "chains-demo"
version = "0.1.0"
edition = "2024"
rust-version = "1.88"The rust-version field is optional. It makes Cargo report a clear message on an older toolchain, instead of a syntax error pointing at &&. To check your compiler, run rustc --version. To move an existing crate to the new edition, run cargo fix --edition and then change the edition field.
Choosing a let chain
A let chain is the right tool when several conditions must hold together, later ones depend on earlier bindings, and the failure path is a single fallback. Other constructs fit better in these cases:
- One pattern with a different response for every variant: use
match. - Unwrap or exit early, keeping the happy path unindented: use
let else. Chains bind names only inside the success block. - A boolean answer with no bindings: use
matches!. - Different fallbacks for different failing checks: nested
if letormatchstill reads better, because a chain has just oneelse.
Common mistakes
- Expecting bindings in
else. If you need to report which step failed, a chain loses that information. Usematchon a tuple, or separate checks. - Consuming values in a failing link.
while let Some(x) = it.next() && cond(x)discards the element that failedcond. - Putting a side effect in a late link and forgetting short-circuiting. The link might never run.
- Forgetting the edition. The feature gate is the crate edition, not only the compiler version.
Exercise
Rewrite this function with a single let chain. Which edition and minimum Rust version do you need, and why can't the else branch use n?
fn first_even(items: &[&str]) -> Option<i32> {
if let Some(first) = items.first() {
if let Ok(n) = first.parse::<i32>() {
if n % 2 == 0 {
return Some(n);
}
}
}
None
}
Show answer
Use if let Some(first) = items.first() && let Ok(n) = first.parse::<i32>() && n % 2 == 0 { Some(n) } else { None }. The function body becomes this one expression. You need edition 2024 and Rust 1.88 or newer. The else branch cannot use n because it runs when any link fails, including the first, and at that point n has never been bound.
Exercise
In while let Some(item) = queue.pop() && item >= 0 { ... }, what happens to the first negative item, and how would you stop at a negative item without removing it?
Show answer
The pop call has already removed the item from the vector when the item >= 0 link fails, so the loop ends and that item is dropped. To leave it in place, test the last element first, for example while let Some(&item) = queue.last() && item >= 0 { queue.pop(); ... }. The last call only borrows the element, and the borrow ends before pop runs because item is copied out.