Sub topic 9
The nesting problem with chained if let
This chapter assumes you know Option and Result, match, and the basics of if let. It shows what goes wrong when several if let checks depend on each other. The next chapters on let else and let chains fix that problem.
One check is fine
A single if let is compact. It tests one pattern and runs a block when the pattern matches. The trouble starts when the second check needs a value that the first check produced. Each dependent check has to sit inside the block of the previous one, because the binding only exists there.
Three checks, three levels
Suppose you want to take an optional string, parse it as a number, and accept it only if it is positive. That is two pattern matches and one boolean test.
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));
}The code is correct, but the real work, the return line, is indented three levels. Each extra condition pushes it further right. This is the rightward drift problem. Readers have to track which braces are still open to know what must be true at the innermost line.
The fallback also lives far away from the checks. Every failure path jumps to the single line after the outer if let. If a different failure needed a different result, you would have to add an else at each level.
fn label(first: Option<&str>) -> &'static str {
if let Some(text) = first {
if let Ok(n) = text.parse::<i32>() {
if n > 0 {
"positive"
} else {
"not positive"
}
} else {
"not a number"
}
} else {
"no input"
}
}
fn main() {
println!("{}", label(Some("7")));
println!("{}", label(Some("x")));
println!("{}", label(None));
}Here each else sits at the end of its block, far from the if let it belongs to. Matching the three else branches to their conditions takes careful reading.
Why you cannot just flatten it
You might try to write the checks one after another at the same level. That does not work, because a binding made by if let is visible only inside that if let block. After the block ends, text and n are gone. Nesting is the only way to keep a binding alive for the next check.
Workarounds and their costs
You can flatten the checks with Option methods. Here and_then chains the fallible step, and filter handles the boolean test.
fn describe(first: Option<&str>) -> String {
match first.and_then(|t| t.parse::<i32>().ok()).filter(|&n| n > 0) {
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 removes the nesting, but it has costs:
.ok()throws away the parse error, so you can no longer tell "not a number" from "no input".- Closures and combinator names are harder to read than patterns for some people, and they get worse as the logic grows.
- Early
returnorbreakinside a closure only leaves the closure, not the function.
Another option is to extract each level into a helper function. That can help, but it adds names and signatures for logic that is used once.
What the problem calls for
The nesting exists for two reasons. Bindings need to stay in scope for later checks, and a pattern match cannot be combined with a boolean test in one condition. A good fix has to address both. let else addresses the scope part by keeping the binding in the surrounding scope. Let chains address the combining part by joining patterns and conditions in a single if. The following chapters cover each.
Exercise
In the describe function with three nested checks, why can't you place the if let Ok(n) = text.parse::<i32>() check after the closing brace of the outer if let Some(text) = first block?
Show answer
The binding text exists only inside the outer if let block. Outside it, text is out of scope, so the parse call cannot compile. Any check that uses text must stay inside that block, which is what forces the nesting.