Sub topic 7
let else: unwrap or leave early
This chapter assumes you know the basics of Option and Result, how match works, and the difference between refutable and irrefutable patterns. It also assumes you have read the if let chapters. Everything here compiles on stable Rust 1.65 or newer in any edition.
What let else does
A refutable pattern can fail to match. let normally accepts only irrefutable patterns, so let Some(x) = opt; is a compile error. let else lets you use a refutable pattern in a let statement if you say what happens when it fails:
let PATTERN = EXPRESSION else { DIVERGING_BLOCK };If the pattern matches, its bindings are introduced in the surrounding scope and execution continues with the next statement. If it doesn't match, the else block runs, and that block must never fall through.
The main benefit is where the bindings live. With if let, they exist only inside the block. With let else, they exist for the rest of the enclosing block, so the success path stays at the same indentation level.
fn parse_port(input: &str) -> Result<u16, String> {
let Ok(port) = input.trim().parse::<u16>() else {
return Err(format!("invalid port: {input}"));
};
Ok(port)
}
fn main() {
println!("{:?}", parse_port(" 8080 "));
println!("{:?}", parse_port("abc"));
}This prints Ok(8080) and then Err("invalid port: abc"). After the let statement, port is a plain u16 in scope. No Option or Result wrapper remains.
The equivalent match
let else is shorthand for a match in which one arm yields the binding and the other leaves the scope:
fn parse_port_match(input: &str) -> Result<u16, String> {
let port = match input.trim().parse::<u16>() {
Ok(port) => port,
Err(_) => return Err(format!("invalid port: {input}")),
};
Ok(port)
}
fn main() {
println!("{:?}", parse_port_match("443"));
println!("{:?}", parse_port_match("-1"));
}The match version repeats the name port and needs an explicit arm for the failure case. let else removes that repetition. The cost is that the failure branch cannot see the error value. In let Ok(port) = ... else { ... }, the Err(e) payload is not bound, so you can't include it in the message. If you need it, use match, map_err with ?, or if let.
Where the bindings go
The bindings follow the normal rules of a let statement. They are visible from the end of the statement to the end of the enclosing block. They are not visible inside the else block, because that block runs only when the pattern did not match and nothing was bound.
You can shadow an existing name. This is a common idiom for unwrapping an optional parameter:
fn first_word_len(line: Option<&str>) -> usize {
let Some(line) = line else {
return 0;
};
let Some(word) = line.split_whitespace().next() else {
return 0;
};
word.len()
}
fn main() {
println!("{}", first_word_len(Some("hello world")));
println!("{}", first_word_len(Some(" ")));
println!("{}", first_word_len(None));
}This prints 5, 0, and 0. Each let else peels off one layer of absence. The function body stays flat no matter how many such steps you chain.
Moves and borrows
A pattern that binds by value moves out of the expression, exactly as in match. If the matched value is not Copy, the original may become partly or fully unusable. To keep the original, match on a reference:
fn main() {
let name: Option<String> = Some(String::from("Ada"));
let Some(n) = &name else {
println!("no name");
return;
};
println!("hello, {n}");
println!("still have {name:?}");
}Here n is a &String thanks to default binding modes, and name remains usable afterwards.
Why the else block must diverge
The compiler requires the else block to have type !, the never type. It means "this code does not complete normally." The reason is soundness. If the pattern fails, the bindings after the statement would be uninitialized. The compiler can only allow later code to use them if the failure path never reaches that code.
The following expressions diverge, so they can end an else block:
returnorreturn valuebreakandcontinue, including labeled formspanic!,unreachable!,todo!,unimplemented!std::process::exit(code)- an infinite
loop {}with nobreak - a call to any function that returns
!
A block that prints and then falls off the end has type (), and the compiler rejects it with a type mismatch error that mentions !. Printing first is fine, as long as the block ends with a diverging expression.
Choosing the exit
The right diverging expression depends on the context:
| Context | Typical else body | Effect |
|---|---|---|
| Function returning `Result` | `return Err(...)` | Report the failure to the caller |
| Function returning `Option` | `return None` | Propagate absence |
| Loop over items | `continue` | Skip this item |
| Search loop | `break` | Stop looking |
| Invariant that cannot fail | `panic!("...")` | Crash with a message |
| Command-line program | `std::process::exit(2)` | End the process |
Here is a loop that skips bad input, with a HashMap lookup as the refutable step:
use std::collections::HashMap;
fn total_for(prices: &HashMap<String, u32>, items: &[&str]) -> u32 {
let mut total = 0;
for item in items {
let Some(price) = prices.get(*item) else {
eprintln!("skipping unknown item: {item}");
continue;
};
total += price;
}
total
}
fn main() {
let mut prices = HashMap::new();
prices.insert(String::from("apple"), 3);
prices.insert(String::from("pear"), 5);
println!("{}", total_for(&prices, &["apple", "kiwi", "pear"]));
}The unknown item kiwi is reported on standard error, and the program prints 8.
Restrictions on the expression
Two rules about the right-hand side catch people out.
- The expression cannot end with a closing brace
}. Something likelet Some(x) = if cond { a } else { b } else { return };is rejected, because it is hard to tell whichelsebelongs to what. Wrap the expression in parentheses, or bind it to a variable on the previous line. The same applies to a barematchor block as the expression. - The expression cannot be a bare
&&or||expression. Parenthesize it if you really need one. In practice this is rare, since patterns usually match on a value, not on a boolean.
The compiler error for each case tells you to add parentheses, so you can fix it quickly when you hit it.
Patterns beyond Option and Result
Any refutable pattern works, including enum variants with fields, nested structures, slices, and ranges:
enum Command {
Move { x: i32, y: i32 },
Say(String),
Quit,
}
fn run(cmd: Command) -> String {
let Command::Move { x, y } = cmd else {
return String::from("not a move command");
};
format!("moving by ({x}, {y})")
}
fn main() {
println!("{}", run(Command::Move { x: 2, y: -1 }));
println!("{}", run(Command::Say(String::from("hi"))));
println!("{}", run(Command::Quit));
}This is useful when you expect one variant and everything else is an error or an early exit. If you need to handle two or three variants differently, a match is clearer, because each outcome is visible in one place.
let else versus the alternatives
- Compared to
if let: uselet elsewhen the failure path exits and the success path is the main body of the function. Useif letwhen both paths continue and the bindings are only needed in a small block. - Compared to
?: the?operator is shorter when you want to propagate anErrorNoneunchanged. Chooselet elsewhen you need to convert the failure into a custom value or a log message, or when you are in a loop and wantcontinue. - Compared to
match: usematchwhen each case produces different behavior or you need the payload of the failing case. - Compared to
unwraporexpect:let Some(x) = opt else { panic!("...") };is equivalent toexpect, but lets you destructure a more complex pattern in the same statement.
A rule of thumb: if you find yourself writing if let ... { ... } else { return ...; } where the if branch holds almost all of the function, switch to let else.
Common mistakes
- Forgetting the trailing diverging statement in the
elseblock, which causes a type mismatch. - Trying to use pattern bindings inside the
elseblock. They are not in scope there. - Expecting the original value to remain usable after a by-value binding moved a non-
Copypayload out of it. - Using a trailing-brace expression on the right-hand side without parentheses.
- Using
let elsewhere you needed the error value, and then discarding it silently.
Exercise
The function below fails to compile. Explain why, and fix it so that it prints a message and returns 0 when the input is not a valid number. fn double(input: &str) -> i32 { let Ok(n) = input.parse::<i32>() else { println!("not a number: {input}"); }; n * 2 }
Show answer
The else block ends with the println! statement, so its type is () and not the never type !. If the pattern failed, execution would continue to n * 2 with n unbound, so the compiler rejects it. Add a diverging statement at the end of the block: let Ok(n) = input.parse::<i32>() else { println!("not a number: {input}"); return 0; };. The block still prints, then leaves the function.
Exercise
Write a function longest_line_len(text: &str) -> usize that uses let else inside a loop over text.lines() to skip any line that does not contain a colon (use line.split_once(':')), and returns the length of the longest value found after a colon. Why is continue the right diverging expression here?
Show answer
fn longestlinelen(text: &str) -> usize { let mut longest = 0; for line in text.lines() { let Some((, value)) = line.splitonce(':') else { continue; }; longest = longest.max(value.trim().len()); } longest } continue is right because a line without a colon is not an error for the whole function. It should only be skipped, and the loop should move on to the next line. return would stop the search early, and panic! would crash on harmless input.