Sub topic 13
Choosing between match, if let, let else, and let chains
This chapter assumes you know Option and Result, basic match, and borrowing. It also assumes you have seen each construct from the earlier chapters. Here you will pick one for a given piece of code.
Start from what you need
Each construct answers a different question. Ask these in order:
- Do you need to handle every shape of the value, or does each variant get different work? Use
match. - Do you only want a yes or no answer, with no bindings? Use
matches!. - Do you want to run code for one pattern and ignore the rest? Use
if let. - Do you want to unwrap a value and leave the function if it is missing? Use
let else. - Do you need several patterns and conditions to all hold? Use a let chain.
- Do you need to repeat while a pattern keeps matching? Use
while let.
One example using several constructs
The function below looks up an order, leaves early if it is missing, and then uses a let chain for the optional part.
use std::collections::HashMap;
// Requires Rust 1.88 or newer and edition = "2024" in Cargo.toml.
fn shipping_label(orders: &HashMap<u32, String>, id: u32) -> Result<String, String> {
let Some(name) = orders.get(&id) else {
return Err(format!("no order {id}"));
};
if let Some(first) = name.split_whitespace().next()
&& first.len() > 1
{
Ok(format!("Ship to {first}"))
} else {
Ok(String::from("Ship to customer"))
}
}
fn main() {
let mut orders = HashMap::new();
orders.insert(1, String::from("Ada Lovelace"));
orders.insert(2, String::from("X"));
println!("{:?}", shipping_label(&orders, 1));
println!("{:?}", shipping_label(&orders, 2));
println!("{:?}", shipping_label(&orders, 3));
let maybe = Some(5);
println!("{}", matches!(maybe, Some(n) if n > 3));
}The let else handles the failure case first, so the rest of the function is not indented. The let chain checks the pattern and the length together, so there is one else branch instead of two. The matches! line returns a bool and binds nothing outside its guard.
Comparing the constructs
| Construct | Binds names | Else behavior | Best for |
|---|---|---|---|
| `match` | Per arm | Must cover all cases | Several outcomes, exhaustiveness checks |
| `matches!` | No | Returns `false` | Boolean tests and filters |
| `if let` | In the block | Optional `else` | One interesting case |
| `let else` | In the outer scope | Must diverge | Unwrap or exit early |
| let chain | In the block | Optional `else` | Patterns mixed with conditions |
| `while let` | In the body | Loop ends | Draining a stack, queue, or iterator |
Common mistakes
- Using
if letwithelse if letfor four or five variants. Amatchis clearer and the compiler warns you when you forget a variant. - Using
let elsewhen the failure case should not leave. Theelseblock must diverge, so useif letormatchinstead. - Using a let chain on an older toolchain. It fails to compile before Rust 1.88, and in edition 2021 even on newer compilers.
- Writing
match x { Some(_) => true, _ => false }. Usematches!(x, Some(_)), orx.is_some()forOption.
A practical rule
Start with the construct that matches your intent. Switch to match when a second interesting case appears. Reach for let else when the code below depends on the value being present. Use a let chain when you would otherwise nest more than one level of if let.
Exercise
You are writing a function that reads an optional config string, parses it as a u16 port, and returns an error if either step fails. After that, 40 lines of code use the port. Which construct do you use, and why? Would a let chain help?
Show answer
Use let else for each step (or one let Ok(port) = ... else { return Err(...) }; after the unwrap). It binds port in the surrounding scope, so the 40 lines stay unindented, and the else block exits the function. A let chain would not help here, because its bindings exist only inside the block that follows it, and the code after it needs port in the outer scope.