The Analogy: The Night Porter's Peephole
A night porter does not run the daytime sorting procedure for every knock at the door. They slide the peephole cover across, look, and if it is the courier with the overnight bag, they open the door and take the bag in. If it is anything else, the cover slides shut and nothing further happens. One question, one action, and no obligation whatsoever to have a plan for every possible visitor.
The cost of that convenience is real, and it is worth naming before you enjoy it. The daytime procedure has a supervisor who checks that every category of caller is accounted for -- couriers, cleaners, contractors, the occasional lost guest. The peephole has no supervisor. If a new kind of delivery starts arriving at three in the morning, the porter will simply not open the door, and nobody will be told that a case was missed. The silence is the whole trade.
Sometimes there is a second question worth asking: if not the courier, then perhaps the cleaner. The porter can look again, and again, and the door still opens for exactly one kind of caller at a time. But by the third or fourth cover-slide it has stopped being a shortcut, and the daytime procedure -- one list, checked once, with the supervisor watching -- would have been both shorter and safer.
And when the deliveries arrive in a queue, the porter keeps opening the door for as long as there is another bag on the step, and stops the moment there is not. That last shape is a loop whose condition and whose unpacking are the same act: keep going while the answer to the one question is "yes, here is another one".
Syntax or Core Structure
if let takes a pattern and a value, and runs its block only if the pattern matches -- binding whatever the pattern names for the duration of that block.
enum Slot {
Empty,
Parcel { id: u32, kg: u32 },
Note(String),
}
fn main() {
let slots = [
Slot::Parcel { id: 41, kg: 3 },
Slot::Note(String::from("ring twice")),
Slot::Empty,
];
for s in &slots {
if let Slot::Parcel { id, kg } = s {
println!("took parcel {id} at {kg} kg");
}
}
println!();
let stored: Option<u32> = None;
if let Some(kg) = stored {
println!("stored weight {kg}");
} else {
println!("nothing stored");
}
println!();
for s in &slots {
if let Slot::Parcel { id, .. } = s {
println!("parcel {id}");
} else if let Slot::Note(text) = s {
println!("note: {text}");
} else {
println!("slot empty");
}
}
println!();
let mut queue = vec![10, 20, 30];
while let Some(top) = queue.pop() {
println!("popped {top}, {} left", queue.len());
}
}
Output:
took parcel 41 at 3 kg
nothing stored
parcel 41
note: ring twice
slot empty
popped 30, 2 left
popped 20, 1 left
popped 10, 0 left
Four shapes in one program. The first loop is the bare if let: one case of interest, and the other two slots pass by without a line of code mentioning them. The second block adds an else, which is what you want when the absence is itself worth reporting. The third is an else if let chain, and it is the shape to be suspicious of -- three questions asked one at a time, doing the job a match would do in one. The fourth is while let, where the loop's condition and its unpacking are a single act.
There is one diagnostic worth knowing, because it catches a genuine slip:
warning: irrefutable `if let` pattern
--> src/main.rs:4:8
|
4 | if let x = value {
| ^^^^^^^^^^^^^
(rustc adds a note that the pattern will always match and a help suggesting a plain let; both are trimmed here.) A pattern that cannot fail makes the if meaningless -- the block always runs -- and the usual cause is a variant name typed as a lowercase identifier, which Rust reads as a fresh binding rather than as the variant you meant.
Technical Depth: One Question, and What It Costs
It is sugar, and it is still an expression
if let PAT = EXPR { A } else { B } is exactly match EXPR { PAT => A, _ => B }. Nothing is faster, nothing is slower, and no capability is added -- the only change is the shape on the page. With no else, the elided arm is _ => (), which is why a bodiless if let must evaluate to the unit type.
Because it is an expression, it can produce a value, and then both branches must agree on the type.
fn main() {
let raw: Option<&str> = Some("9000");
let port: u16 = if let Some(text) = raw {
text.parse().unwrap_or(8080)
} else {
8080
};
println!("port {port}");
let flag: Option<bool> = Some(true);
if let Some(true) = flag {
println!("flag set");
}
let label = if let Some(text) = raw { text } else { "unset" };
println!("label {label}");
}
Output:
port 9000
flag set
label 9000
Three uses, three roles. The first if let is the right-hand side of a let, so both branches have to produce a u16. The second has no else and no value, so its block must evaluate to () -- and its pattern is Some(true), a literal nested inside the variant, which is a reminder that if let accepts every pattern match does. The third is the one-line form that replaces a match when you want a value and a fallback and nothing else.
Note also that all three read raw and raw survives, because Option<&str> is Copy. With an Option<String> the first if let Some(text) = raw would move the string out and the later uses would be error[E0382]. Matching against a reference -- if let Some(text) = &raw -- is the fix you will reach for; raw.as_ref() and an outright clone are the other two.
Choosing a form
| Form | Checks every case | Binds | Reach for it when |
|---|---|---|---|
match | yes | yes | there are three or more outcomes, or a new variant must be caught |
if let | no | yes | exactly one shape matters and the rest need nothing |
if let with else | no | yes | one shape matters and there is a single fallback |
else if let chain | no | yes | two shapes, and a match would need awkward nesting |
while let | no | yes | draining a source until it stops producing |
let with else | no | yes | the shape is required and the failure path diverges |
matches! | no | no | you want a plain bool, typically inside a filter |
The "checks every case" column is the whole decision. Only match will fail to compile when a variant is added, so only match protects a piece of logic that must be revisited every time the type grows. Everything else in that table is a deliberate opt-out, and the right way to think about it is: if a new variant appeared tomorrow, would silence be the correct behaviour here? For a metrics counter or a cache-warming pass, yes. For pricing, billing, or access control, no.
let with else, and while let that stops
struct Job {
id: u32,
owner: Option<String>,
}
fn assign(j: &Job) -> String {
let Some(owner) = &j.owner else {
return format!("job {} unassigned", j.id);
};
format!("job {} owned by {owner}", j.id)
}
fn main() {
let jobs = [
Job { id: 1, owner: Some(String::from("ada")) },
Job { id: 2, owner: None },
];
for j in &jobs {
println!("{}", assign(j));
}
let mut items = vec![Some(1), Some(2), None, Some(4)];
items.reverse();
let mut sum = 0;
while let Some(Some(n)) = items.pop() {
sum += n;
}
println!("sum {sum}, {} left", items.len());
}
Output:
job 1 owned by ada
job 2 unassigned
sum 3, 1 left
let ... else is the shape for a precondition. Its pattern is refutable, which a plain let forbids, and the price is that the else block must diverge -- return, break, continue, or a panic. In exchange, the binding lives in the enclosing scope rather than inside a block, so the rest of the function stays at one level of indentation instead of drifting right with every check.
The while let result is the one to remember. items after reverse is [Some(4), None, Some(2), Some(1)], so pop yields Some(Some(1)) and Some(Some(2)), giving sum = 3. The next pop returns Some(None), which does not match Some(Some(n)), so the loop ends -- it does not skip that entry and continue. And the entry is gone regardless, because pop already removed it before the pattern was tested. One element remains. A loop that should skip rather than stop needs for plus an inner if let, or .flatten().
matches! when you only want a bool
fn main() {
let values = [Some(3), Some(12), None];
let mut small = 0;
for v in values {
if matches!(v, Some(n) if n < 10) {
small += 1;
}
}
println!("small {small}");
println!("lowercase: {}", matches!('x', 'a'..='z'));
println!("digit: {}", matches!('X', '0'..='9'));
}
Output:
small 1
lowercase: true
digit: false
matches! expands to a match returning true for your pattern and false for everything else, and it accepts a guard. It is the honest choice whenever the answer you want is a boolean rather than a branch -- inside filter, retain, assert!, or a plain if. Writing if let Some(_) = opt { true } else { false } says the same thing in four times the space.
Let chains
Two let bindings and a condition can be chained with && inside one if:
if let Some(user) = &session.user
&& let Some(team) = &user.team
&& team.active
{
println!("{} is on {}", user.name, team.name);
}
Each binding is in scope for the rest of the chain and for the block. This is stable from Rust 1.88, and only in edition 2024 -- on an older compiler or an older edition the same code needs one if let nested inside another, with the plain condition innermost. Check your edition in Cargo.toml before reaching for it, because the failure mode is a syntax error rather than anything descriptive.
Real World Example: Following a Redirect Chain
A site keeps a table of old paths and where they now point. Resolving a URL means following that table until it stops pointing anywhere, then looking up the page -- and both halves of that sentence are a pattern-with-a-binding.
enum Outcome {
Found { path: String, title: String, hops: u32 },
Missing { path: String },
TooManyHops { last: String },
}
struct Site {
redirects: Vec<(String, String)>,
pages: Vec<(String, String)>,
}
impl Site {
fn redirect_of(&self, path: &str) -> Option<&str> {
self.redirects
.iter()
.find(|(from, _)| from.as_str() == path)
.map(|(_, to)| to.as_str())
}
fn title_of(&self, path: &str) -> Option<&str> {
self.pages
.iter()
.find(|(p, _)| p.as_str() == path)
.map(|(_, t)| t.as_str())
}
fn resolve(&self, start: &str) -> Outcome {
let mut path = start;
let mut hops = 0;
while let Some(next) = self.redirect_of(path) {
hops += 1;
if hops > 4 {
return Outcome::TooManyHops { last: path.to_string() };
}
path = next;
}
let Some(title) = self.title_of(path) else {
return Outcome::Missing { path: path.to_string() };
};
Outcome::Found {
path: path.to_string(),
title: title.to_string(),
hops,
}
}
}
fn summary(o: &Outcome) -> String {
match o {
Outcome::Found { path, title, hops: 0 } => format!("{title} at {path}"),
Outcome::Found { path, title, hops } => format!("{title} at {path} after {hops} hops"),
Outcome::Missing { path } => format!("no page at {path}"),
Outcome::TooManyHops { last } => format!("redirect loop, gave up at {last}"),
}
}
fn main() {
let site = Site {
redirects: vec![
(String::from("/old-home"), String::from("/home")),
(String::from("/home"), String::from("/")),
(String::from("/a"), String::from("/b")),
(String::from("/b"), String::from("/c")),
(String::from("/c"), String::from("/d")),
(String::from("/d"), String::from("/e")),
(String::from("/e"), String::from("/f")),
],
pages: vec![
(String::from("/"), String::from("Front page")),
(String::from("/pricing"), String::from("Pricing")),
],
};
let starts = ["/", "/old-home", "/pricing", "/missing", "/a"];
for s in starts {
println!("{:<10} {}", s, summary(&site.resolve(s)));
}
println!();
let mut indexed = 0;
for s in starts {
if let Outcome::Found { title, hops, .. } = site.resolve(s) {
indexed += 1;
println!("indexing {title} after {hops} hops");
}
}
println!("\nindexed {indexed} of {} starts", starts.len());
}
Output:
/ Front page at /
/old-home Front page at / after 2 hops
/pricing Pricing at /pricing
/missing no page at /missing
/a redirect loop, gave up at /e
indexing Front page after 0 hops
indexing Front page after 2 hops
indexing Pricing after 0 hops
indexed 3 of 5 starts
The whole redirect walk is one while let. The loop's condition is the question "does this path point somewhere else?", and the binding next is the answer, in scope exactly where it is needed. The alternative -- loop, then match self.redirect_of(path), then Some(next) => path = next, then None => break -- is four more lines saying the same thing, and it puts the interesting assignment two levels deep. When a loop should run for as long as a lookup keeps succeeding, while let is not a shortcut, it is the direct statement.
let Some(title) = self.title_of(path) else { return ... }; is the precondition shape. Everything after it is the successful case, unindented, with title in scope as a plain &str. Written as if let, the final Outcome::Found construction would sit inside a block, and the Missing case -- the boring one -- would be the outer, visually dominant branch. let ... else inverts that: the failure exits early, and the reader's eye stays on the path that matters.
The last loop is where the choice becomes a design decision rather than a style preference. Indexing cares about exactly one outcome, so if let Outcome::Found { .. } is right, and the two ignored cases cost nothing -- no _ => {} arm, no comment explaining that nothing happens. Meanwhile summary is a match, because there all three outcomes have something to say. Now add a fourth variant, say Outcome::Gone: summary stops compiling and demands a decision, while the indexing loop keeps working and silently skips it. That asymmetry is the point. The reporting code must be revisited; the indexer genuinely should not care.
Three honest limits. redirect_of and title_of do a linear scan over a Vec<(String, String)>, which is fine for a handful of rules and wrong for a site map -- a HashMap is the real structure, and that is M4. The hop limit of 4 is arbitrary, and more importantly a limit cannot tell a long legitimate chain from a two-step cycle; a set of visited paths would report the loop honestly instead of guessing. And every Outcome allocates three Strings with to_string() where borrowed &str tied to the site's lifetime would do, which is the trade you make to keep Outcome free of lifetime parameters until M6.
Common Mistakes
- Reaching for
if letwhere the unmatched case actually matters. This is the one mistake that costs money.if let Band::Letter { .. } = band { charge(85) }prices letters and silently charges nothing for everything else, and it will keep doing so after three more bands are added. Before writingif let, answer the question honestly: if a new variant appeared tomorrow, is doing nothing the correct behaviour? If the answer is no, you want amatch.
- Expecting
while letto skip the items that do not match. It stops at the first mismatch.while let Some(Some(n)) = items.pop()over[Some(1), None, Some(2)]sums the entries before theNoneand abandons the rest -- and theNoneitself has already been removed, becausepopran before the pattern was tested. When you want "skip and keep going", use aforloop with anif letinside, or.flatten().
- Using a binding after its block has ended.
if let Some(port) = raw { }followed byprintln!("{port}")iserror[E0425], "cannot find value in this scope". The binding exists only inside the block, which is exactly whylet...elseexists: it puts the binding in the enclosing scope so the rest of the function can use it.
- Being surprised by deliberate shadowing.
if let Some(config) = config { ... }is idiomatic, and inside the blockconfigis the unwrapped payload while outside it is still theOption. That is fine when the block is three lines and confusing when it is thirty. Keep shadowed blocks short, or give the inner binding its own name when both meanings are live in the reader's head.
- Typing a variant name in lowercase.
if let empty = slot { ... }does not test forSlot::Empty; it binds the whole slot to a new variable calledemptyand always runs the block. Theirrefutable_let_patternswarning is the only signal, and it is easy to miss in a busy build. Import variants explicitly or write the full path so a typo is a name error rather than a new binding.
- Stacking
if letthree or four deep. Each level adds a brace, an indent, and a mental "and if that one failed?". Two levels is usually fine; at three, the honest options are amatchon a tuple, a chain oflet...elsepreconditions, or -- on edition 2024 -- a let chain. The nesting is not a style crime, it is a signal that the code is asking several questions and pretending to ask one.
- Using
if letto produce a value that a combinator already produces.if let Some(n) = opt { n * 2 } else { 0 }isopt.map_or(0, |n| n * 2).if let Some(n) = opt { n } else { 8080 }isopt.unwrap_or(8080). Neither combinator is shorter by accident: they say "transform or substitute" where theif letsays "branch", and only one of those is what you meant.
- Writing
if let Some(_) = optas a boolean test. If you are not using the payload, you are asking a yes-or-no question, andopt.is_some()asks it directly. Where the question involves a pattern rather than a variant,matches!is the tool --matches!(slot, Slot::Parcel { kg, .. } if kg > 10)reads as a predicate because it is one.
- Writing a
let...elsewhoseelseblock does not diverge.let Some(port) = raw else { 8080 };looks like it supplies a default and is rejected: theelseblock mustreturn,break,continue, or panic, because there is no other way to leaveportunbound. rustc says so directly, that theelseclause does not diverge. If what you wanted was a default value, that isunwrap_or, notlet...else.
Best Practices
- Use
if letwhen exactly one shape matters and the others need nothing done. That is its whole job, and within that job it is clearer than amatchwith a_ => {}arm, because it does not give the ignored cases equal visual weight.
- Switch to
matchthe moment a second outcome needs its own behaviour. Twoif letblocks in sequence over the same value, or anelse if letchain three long, is amatchthat has not been written yet -- and thematchgets you exhaustiveness for free.
- Use
let...elsefor preconditions, so the happy path never indents. Three checks at the top of a function, each with a divergingelse, leave the real work at one level. The same three as nestedif letblocks leave it at four.
- Prefer combinators for one-line value production.
unwrap_or,unwrap_or_else,map_orandand_thenexpress "substitute" and "transform" without a branch, and they compose where anif letdoes not.
- Use
matches!whenever the answer is abool. Insidefilter,retain,assert!or a plainif, it is both shorter and more honest than anif letwhose only purpose is to reachtrue.
- Match against a reference in
if letunless the block must own the data.if let Some(text) = &rawleavesrawintact for the rest of the function;if let Some(text) = rawmoves the payload out of any non-CopyOption.
- Put a bound on any
while letthat follows data you do not control. Redirect chains, parent pointers and retry queues can all cycle. A hop counter is the cheap guard; a set of visited keys is the honest one, because it can tell you that there was a loop rather than only that you gave up.
- Say out loud what silence means. When you choose
if letovermatchon a type that will grow, that is a decision, and a one-line comment recording it ("new variants are deliberately not indexed") is worth more than the four lines thematchwould have cost.
Practice Exercises
- Watch exhaustiveness disappear. Take the
Slotenum from the Syntax section and writefn fee(s: &Slot) -> u32as an exhaustivematch. Now rewrite it as anif let/else if let/elsechain returning the same numbers, and confirm both versions agree on all three slots. Then add a fourth variantSlot::Pallet { kg: u32 }and compile both. Record which one failed, what it said, and what the other one now returns for a pallet.
- Stop versus skip. Write a function that sums the numbers in a
Vec<Option<i32>>usingwhile let Some(Some(n)) = list.pop(), and print both the sum andlist.len()afterwards for the input[Some(1), None, Some(5), Some(2)]. Then write a second function producing the total of all theSomevalues in the same input without changing the data, and note which construct you had to reach for and whywhile letcould not do it.
- Flatten with
let...else. Givenstruct Order { customer: Option<Customer> },struct Customer { address: Option<Address> }andstruct Address { postcode: Option<String> }, writefn postcode(o: &Order) -> Stringtwice: once as three nestedif letblocks with a fallback string, and once as threelet...elsestatements each returning early. Count the maximum indentation depth of both versions and the number of times the fallback string appears in each.
- Pick the right tool three times. For
let slots: Vec<Slot>, write (a) a count of slots holding a parcel over 10 kg, (b) aVec<u32>of every parcel id, and (c) a single line that reports whether any slot is a note. Usematches!for exactly one of them,if letinside a loop for exactly one, and a method on the iterator for the third -- then write two sentences justifying which went where.