Sub topic 9
The nesting problem with chained if let
This chapter assumes you know Option and Result, the basic if let form with an optional else, and how a block limits the lifetime of a variable. It covers what goes wrong when several if let checks depend on each other, and why that shape motivates the features in the next chapters.
What the problem looks like
Suppose you have an optional string. If it is present, you parse it as a number. If the parse succeeds, you check that the number is positive. Only when all three steps pass do you have something to use.
Written with plain if let and if, each step goes inside the previous one:
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));
}This prints positive number 42, then no positive number twice. The code is correct, but it has two weaknesses:
- Rightward drift. The useful line, the one that builds the result, sits three levels deep. Every extra step adds a level of indentation and another closing brace.
- A failure path that is far from its cause. The three failures (
None, a parse error, a non-positive number) all end in the same fallback line at the bottom. A reader has to trace the braces to see that.
Why the nesting happens
The nesting follows from how scope works, not from a style choice.
if let Some(text) = firstbindstextonly inside its block. The next check needstext, so it must be written inside that block.- Each
if letis a separate expression with its own block. Nothing carries a binding from oneif letto the next except nesting. - A plain
&&cannot join twoif letlines in older Rust. A pattern match was a statement-like construct, not a boolean expression.
The dependency between steps is a chain. Step two needs the value from step one, and step three needs the value from step two. A language without a way to express "and then" forces you to express it with containment.
The diagram below uses the required fence form instead.
Three arrows point at the fallback node. In the nested code, the fallback has to be reachable from all three places.
The else duplication problem
The first example has no else branches. It relies on control falling out of the nested blocks to the final line, and it uses return to exit early on success. That works only when a statement after the nest can serve as the fallback.
If you want if to be the final expression of the function, with no return, each level needs its own else:
fn describe(first: Option<&str>) -> String {
if let Some(text) = first {
if let Ok(n) = text.parse::<i32>() {
if n > 0 {
format!("positive number {n}")
} else {
String::from("no positive number")
}
} else {
String::from("no positive number")
}
} else {
String::from("no positive number")
}
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("abc")));
println!("{}", describe(None));
}The same fallback text now appears three times. If the message changes, you must edit three places, and a missed edit is a real bug. Pulling the string into a constant helps with the text, but the three else blocks and the indentation remain.
Not the same as else if let
else if let looks like a cure, but it solves a different problem. It tests alternatives: try pattern A on a value, and if that fails, try pattern B.
fn label(value: Option<i32>, fallback: Result<i32, String>) -> String {
if let Some(n) = value {
format!("from option: {n}")
} else if let Ok(n) = fallback {
format!("from result: {n}")
} else {
String::from("nothing available")
}
}
fn main() {
println!("{}", label(Some(1), Ok(2)));
println!("{}", label(None, Ok(2)));
println!("{}", label(None, Err(String::from("bad"))));
}This stays flat because the branches are independent. Each condition is tested on its own, and none of them uses a binding from an earlier one. Compare:
| Shape | Meaning | Flat with `else if let`? |
|---|---|---|
| A or else B or else C | Alternatives, first match wins | Yes |
| A and then B and then C | Sequence, each step uses the previous binding | No, it nests |
The nesting problem belongs to the second row.
Workarounds before let chains
Several techniques reduce the nesting. Each has a cost.
Combinators on Option
and_then, filter, and map express the chain as method calls:
fn describe(first: Option<&str>) -> String {
first
.and_then(|text| text.parse::<i32>().ok())
.filter(|n| *n > 0)
.map(|n| format!("positive number {n}"))
.unwrap_or_else(|| String::from("no positive number"))
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("-1")));
println!("{}", describe(None));
}This is flat and has one fallback. The price is that .ok() throws away the parse error, closures replace ordinary control flow, and return, break, and ? no longer work inside the closures the way they do in a normal block. Long combinator chains can also be harder to read than the nesting they replace.
Early return with let else
let else unwraps a value or leaves the function, so the success path stays at one indentation level:
fn describe(first: Option<&str>) -> String {
const NONE: &str = "no positive number";
let Some(text) = first else {
return String::from(NONE);
};
let Ok(n) = text.parse::<i32>() else {
return String::from(NONE);
};
if n <= 0 {
return String::from(NONE);
}
format!("positive number {n}")
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("-1")));
println!("{}", describe(None));
}This is flat and keeps the control flow visible. The next chapters explain the rules for the else block. The limits here are that it only works when you can leave the enclosing scope on failure, and that the plain boolean test still needs separate handling.
A helper function with ?
Moving the chain into a function that returns Option lets you use ?:
fn positive_from(first: Option<&str>) -> Option<i32> {
let text = first?;
let n = text.parse::<i32>().ok()?;
if n > 0 { Some(n) } else { None }
}
fn describe(first: Option<&str>) -> String {
match positive_from(first) {
Some(n) => format!("positive number {n}"),
None => String::from("no positive number"),
}
}
fn main() {
println!("{}", describe(Some("42")));
println!("{}", describe(Some("-1")));
println!("{}", describe(None));
}This is clean, but it adds a function whose only purpose is to host the early exits. It also forces you to decide what None means to the caller.
Why a tuple match does not help
A common first idea is match (a, b) with a tuple. That works when the values are independent, but not when the second value is computed from the first. Here text.parse() can run only after first is known to be Some, so there is no tuple to build up front.
Where let chains fit
A let chain removes the scope barrier: it joins pattern matches and boolean conditions with && in a single if. Bindings from earlier links are visible to later links and to the block. The chain stops at the first link that fails and runs the else once.
// 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));
}The three failure arrows from the diagram now merge into one else. The fallback appears once, and the success path has one level of indentation.
Common errors
- Compiling a let chain on an older toolchain or in edition 2021. The compiler rejects
if let ... && let .... Before Rust 1.88 the feature does not exist. On 1.88 or newer withedition = "2021", the compiler reports that let chains need edition 2024. Checkrustc --versionand theeditionline inCargo.toml. - Using
||withlet. A let chain is a conjunction only.if let Some(x) = a || let Some(x) = bis rejected, becausexwould not be bound on every path. Useelse if letor amatchfor alternatives. - Wrapping a
letin parentheses.if (let Some(x) = a) && x > 0is not valid. Write theletwithout parentheses. - Expecting bindings in the else branch. Names bound by the chain exist only in the success block. If the chain fails halfway, the
elsebranch cannot use them, even when earlier links matched. - Moving a value in an early link.
if let Some(text) = firstmovesfirstif the payload is notCopyand is matched by value. Later code cannot usefirst. Match on a reference (&first, orfirst.as_ref()) if you need it afterwards.
Choosing a response to nesting
| Situation | Reasonable choice |
|---|---|
| Two or three dependent checks, with one shared fallback value | Let chain (edition 2024) |
| Failure should leave the function and the success path is long | `let else` |
| Steps all return `Option` or `Result` and you want to propagate | `?` in a helper |
| Pure transformation of an `Option` value | Combinators |
| Independent alternatives | `else if let` or `match` |
Exercise
In the nested if let version of describe that has an else on every level, how many times does the fallback expression appear, and what is the specific feature of let chains that lets it appear only once?
Show answer
It appears three times, once for each of the three levels (the Some check, the parse check, and the n > 0 check). A let chain joins the checks with && in one condition and runs a single else when any link fails, so the fallback is written once.
Exercise
Why can else if let not flatten a sequence of checks where the second check needs a value produced by the first?
Show answer
Each else if let tests its pattern independently and only runs when the earlier test failed, so it can express alternatives. A binding from the first if let exists only inside that first block, so a dependent second check must be nested inside it.