Sub topic 10
let chains: patterns and conditions with &&
This chapter assumes you know Option and Result, basic match, and how if let binds a name inside its block. It covers let chains, which let one if or while combine several pattern matches and boolean tests.
The problem: three levels of nesting
Plain if let handles one pattern. To check a pattern, then a second pattern, then a boolean test, you nest the blocks:
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));
}Each check pushes the useful code one level to the right. The failure case also has to be handled outside all the blocks, so the fallback sits far from the conditions that cause it.
The same logic as a let chain
A let chain joins let patterns and boolean expressions with && in a single condition:
// 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 output is:
positive number 42
no positive number
no positive numberHow a chain is evaluated
- The links are evaluated from left to right.
- Evaluation stops at the first link that fails. A failed pattern or a
falsecondition sends control to theelsebranch, or past theifwhen there is noelse. - A name bound by an earlier
letis visible in every later link and in the block. Heretextis used by the second link, andnis used by the third link and by the block. - Bindings exist only when the whole chain succeeds. You cannot use
nin theelsebranch.
This is the same short-circuit behavior as && on booleans. text.parse never runs when first is None.
Mixing links freely
A chain may contain any number of let links and plain boolean expressions, in any order. You can test a condition first and bind afterward:
fn first_even(values: &[i32]) -> Option<i32> {
if !values.is_empty()
&& let Some(&head) = values.first()
&& head % 2 == 0
{
Some(head)
} else {
None
}
}
fn main() {
println!("{:?}", first_even(&[4, 5]));
println!("{:?}", first_even(&[3, 4]));
println!("{:?}", first_even(&[]));
}while accepts chains too. The loop ends the first time any link fails:
fn main() {
let mut stack = vec![1, 2, 3, 4, 5];
while let Some(top) = stack.pop()
&& top > 2
{
println!("popped {top}");
}
println!("left on the stack: {stack:?}");
}This prints popped 5, popped 4, popped 3, then stops when it pops 2. That value is removed from the stack even though the loop body never ran for it, because pop ran before the test failed. The final line shows [1].
Limits and common errors
||is not allowed. A chain only supports&&. A pattern binding cannot be guaranteed on both sides of an "or", soif let Some(x) = a || let Some(x) = bdoes not compile. Usematchor a nested pattern with|instead.- Parentheses break the chain.
if (let Some(x) = a) && x > 0is rejected.letis allowed only at the top level of the&&sequence. letbinds tighter than you may expect on the right. Inlet Some(x) = a && b, the&&is not part of the scrutinee. The compiler treatsaas the value andbas the next link, so a lazy boolean operator directly in a scrutinee needs parentheses.- Edition and version. On older toolchains or edition 2021, you get an error such as "
letexpressions in this position are unstable". Check bothrustc --versionand theeditionfield inCargo.toml. The next chapter covers these requirements in detail.
Exercise
Rewrite this nested code as a single let chain. What happens to n in the else branch?
fn check(s: Option<&str>) -> bool {
if let Some(t) = s {
if let Ok(n) = t.parse::<u8>() {
if n < 100 {
return true;
}
}
}
false
}
Show answer
Use if let Some(t) = s && let Ok(n) = t.parse::<u8>() && n < 100 { true } else { false }, which can also be shortened to returning the chain's result from the two branches. The name n (and t) is not available in the else branch, because bindings exist only when every link of the chain succeeds.