Sub topic 13
Choosing between match, if let, let else, and let chains
This chapter assumes you know Option and Result, basic match patterns, and ownership and borrowing. You also need to know what refutable and irrefutable patterns are, and what each construct does on its own. Here you will learn how to choose between them. The selection rules are short, and a few of them are easy to get wrong.
Start from the question you are asking
The five tools differ in what happens to the values that do not match. Ask yourself first what the code should do in that case.
| Situation | Construct |
|---|---|
| Every variant needs its own handling, and you want the compiler to flag a new variant | `match` |
| One pattern matters. The rest does nothing, or one shared fallback | `if let` (with optional `else`) |
| One pattern matters, and a mismatch means leaving the function or loop iteration | `let else` |
| Several patterns and boolean tests must all hold, in order | let chain in `if` |
| You need only a true or false answer, with no bindings | `matches!` |
| Repeat while a source keeps producing matching values | `while let` |
match: when exhaustiveness is the point
match is the only construct of the five that forces you to cover every case. That is a feature when the type may grow. If you add a variant to an enum, each match without a wildcard arm stops compiling, and the compiler shows you every place that needs a decision.
enum Command {
Start,
Stop,
Restart { delay_secs: u32 },
}
fn run(cmd: Command) -> String {
match cmd {
Command::Start => String::from("starting"),
Command::Stop => String::from("stopping"),
Command::Restart { delay_secs } => format!("restarting in {delay_secs}s"),
}
}
fn main() {
println!("{}", run(Command::Start));
println!("{}", run(Command::Restart { delay_secs: 3 }));
}If you rewrote this as if let with an else, a new Command::Pause would fall silently into the else branch. Keep match whenever "I forgot a case" would be a bug.
A wildcard arm (_ => ...) removes that protection. Use it when you truly do not care about future variants. If you do care, list the variants explicitly.
if let: one interesting case
Use if let when a match would have one meaningful arm and a throwaway _ => {}. It reads shorter and says "I only care about this shape."
fn main() {
let config_port: Option<u16> = Some(8080);
if let Some(port) = config_port {
println!("listening on {port}");
} else {
println!("using default port");
}
}The trade-off is the loss of exhaustiveness checking. For Option and Result this rarely matters, because the variants will not change. For your own enums it can matter a lot.
Use else if let for two or three different patterns on possibly different values. If you are testing the same value against many patterns, switch back to match.
let else: the early exit
Use let else when the happy path continues after the check and the mismatch case ends the current scope. The binding lands in the surrounding scope, so the rest of the function stays unindented.
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"));
}The else block must diverge. It must end in return, break, continue, a panic, or a call to a function that returns !. If it can fall through, the compiler rejects the code, because port would be unbound afterward.
Prefer let else over if let when the if let body would be most of the function. The signal is a large block indented under one condition, with a short else or no else at all.
Prefer the ? operator over let else when you only want to pass the error up unchanged. let else earns its place when you need to build a new error, log something, or continue a loop.
let chains: several conditions, one block
Before let chains, combining two pattern matches and a boolean test needed three nested 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));
}A let chain joins the same tests with &&:
// 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 links evaluate left to right and stop at the first failure. Bindings from earlier links are visible in later links and in the block. A single else covers every way the chain can fail. You cannot tell which link failed from the else branch, so if the failure reasons need different handling, use separate let else statements or a match.
Limits of let chains
- Chains work only with
&&. There is no||betweenletconditions, because a binding that exists on only one side of anorwould be ambiguous. - Chains work in
ifandwhileconditions. They do not work as the initializer of alet else, solet Some(x) = a && b else { ... }is rejected. - Chains need Rust 1.88 or newer and
edition = "2024". On edition 2021 the compiler reports that let chains are unstable or unavailable, even on a new toolchain.
If you cannot use edition 2024, the fallbacks are nested if let, a match on a tuple, or let else for each step.
while let: repeat while the source delivers
Use while let when the loop is driven by a source that can run dry: pop on a stack, recv on a channel, or next on an iterator you advance by hand.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
}If you are simply walking a collection, for is the better tool. Reach for while let when the body also changes the source, for example when it pushes new work onto the same stack.
matches!: only a yes or no
matches! expands to a match that returns true or false. It is the right choice when you want a boolean and no bindings, such as inside a filter or an assert!. It accepts an optional guard.
fn main() {
let values = [Some(2), None, Some(9), Some(4)];
let big = values.iter().filter(|v| matches!(v, Some(n) if *n > 3)).count();
println!("{big} values above 3");
println!("{}", matches!('k', 'a'..='z'));
}Bindings made inside matches! are not visible outside it. If you need the value afterward, use if let or a let chain.
Putting them together
Real code mixes the constructs. In this example, while let drives the loop, let else skips malformed lines, and a let chain handles a pattern plus a condition.
// Requires Rust 1.88 or newer and edition = "2024" in Cargo.toml.
fn main() {
let mut queue = vec!["web=8080", "db=5432", "bad", "cache=99999", "admin=22"];
while let Some(line) = queue.pop() {
let Some((name, raw)) = line.split_once('=') else {
println!("skip {line}: no '='");
continue;
};
if let Ok(port) = raw.parse::<u16>()
&& port >= 1024
{
println!("{name} listens on {port}");
} else {
println!("{name} has no usable port");
}
}
}The output is:
admin has no usable port
cache has no usable port
skip bad: no '='
db listens on 5432
web listens on 8080The lines come out in reverse order because pop takes from the end of the vector.
Common mistakes
- Using
if let ... else {}on your own enum where a new variant should force a decision. Usematch. - Writing a
let elsewhoseelseblock prints a message and then falls off the end. Addreturn,continue, orbreak. - Expecting
||in a let chain. Split into amatchor into separateifstatements. - Forgetting that
let elseandif letcan move a value out of the scrutinee. Matching onoptby value moves aStringout of anOption<String>. Match on&optor userefwhen you need the original afterward. - Relying on temporaries living through the
elsebranch. In edition 2024, temporaries created in anif letscrutinee are dropped before theelseblock runs. A lock guard taken in the condition is therefore already released insideelse. Code that depended on the older, longer lifetime needs the guard bound to a variable first.
Exercise
A function reads an Option<String> called name and a Result<u32, ParseIntError> called age. It must return an error String immediately if either is missing or invalid, then do about thirty lines of work using both values. Which construct do you use for the checks, and why?
Show answer
Use two let else statements. The mismatch case means leaving the function, so let else keeps the thirty lines of work at the top indentation level, and each else block can return its own specific error. A let chain would hide which check failed, and if let would indent the whole body.
Exercise
You have enum Shape { Circle(f64), Square(f64), Triangle(f64, f64) } and you write if let Shape::Circle(r) = s { ... } else { 0.0 } to compute an area. Next month someone adds Shape::Hexagon(f64). What goes wrong, and what should the code use instead?
Show answer
The hexagon is handled by the else branch and silently gets an area of 0.0, with no compiler warning. A match listing every variant without a wildcard arm fails to compile until the new variant is handled, so the code should use match.
Exercise
Name two reasons a let chain such as if let Some(x) = a && let Some(y) = b might fail to compile on a machine that has a recent Rust installed.
Show answer
The crate may still use edition 2021, since let chains require edition = "2024". Or the toolchain in use may be older than 1.88, for example a pinned version in CI or a rust-toolchain file.