Sub topic 7
let else: unwrap or leave early
This chapter assumes you know Option and Result, match, and the difference between refutable and irrefutable patterns from earlier chapters. It also assumes you have used if let. let else needs Rust 1.65 or newer. Unlike let chains, it needs no special edition.
The problem it solves
You often need a value out of an Option or Result, and if it isn't there, the function can't continue. With if let, the useful code ends up inside the block:
fn port_or_default(input: Option<&str>) -> u16 {
if let Some(text) = input {
if let Ok(port) = text.trim().parse::<u16>() {
return port;
}
}
8080
}
fn main() {
println!("{}", port_or_default(Some("9000")));
println!("{}", port_or_default(None));
}Each check adds one level of indentation, and the main work moves further right.
The syntax
let else takes a refutable pattern on the left of let, an expression on the right, and an else block:
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"));
}If the pattern matches, port is bound in the surrounding scope and execution continues on the next line. If it doesn't match, the else block runs. Note the semicolon after the closing brace. It is required, because this is a let statement.
The key difference from if let is where the binding lives. With if let, the name exists only inside the block. With let else, it exists for the rest of the enclosing scope.
Correction: the diagram must use the required fence form. Here it is.
Stacking several unwraps
Because each let else leaves the happy path flat, several of them read as a list of preconditions:
fn parse_pair(line: &str) -> Result<(String, u16), String> {
let Some((name, value)) = line.split_once('=') else {
return Err(format!("missing '=' in {line:?}"));
};
let Ok(port) = value.trim().parse::<u16>() else {
return Err(format!("invalid port for {}: {}", name.trim(), value.trim()));
};
Ok((name.trim().to_string(), port))
}
fn main() {
println!("{:?}", parse_pair("web = 8080"));
println!("{:?}", parse_pair("web"));
println!("{:?}", parse_pair("web = x"));
}Leaving with something other than return
The else block must diverge. It cannot fall through to the next line, because the bindings would not exist. Inside a loop, continue and break are common exits:
fn main() {
let lines = ["1", "two", "3"];
let mut total = 0;
for line in lines {
let Ok(n) = line.parse::<i32>() else {
println!("skipping {line:?}");
continue;
};
total += n;
}
println!("total = {total}");
}return, break, continue, panic!, and calls to functions returning ! all qualify. The next chapter covers why the compiler insists on this.
Common errors
- Else block falls through. Ending the block with a plain expression or
println!gives a type mismatch error, because the block's type must be!(never). - Missing semicolon.
let elseis a statement and needs the trailing;. - Irrefutable pattern.
let (a, b) = pair else { ... }compiles with a warning, because theelsecan never run. - Using the name inside the else block. The binding does not exist there. Use the original expression's source, such as
input, in your error message. - Lazy boolean expressions. The right side cannot end in
}or be a bare&&/||expression. Wrap it in parentheses if the compiler complains.
When to choose it
Use let else when the failure case means "stop here" and the success case is what the rest of the code needs. Use if let when the matched value is only needed briefly, or when the failure case has its own substantial logic.
Exercise
What is wrong with this code, and how do you fix it? let Some(user) = find_user(id) else { println!("not found"); };
Show answer
The else block does not diverge, so execution would continue without user bound, and the compiler rejects it. Add an exit such as return; (or return Err(...), continue, or break depending on context) after the println!.