if let, let else & while let
These constructs match one pattern when a full match is heavy. let else provides early return on mismatch.
Search across all documentation pages
These constructs match one pattern when a full match is heavy. let else provides early return on mismatch.
fn main() {
let v = Some(10);
if let Some(n) = v {
println!("{n}");
}
let Some(n) = v else {
panic!("expected Some");
};
println!("forced {n}");
}When to reach for this: Optional unwrapping, loop until None, and guard clauses with let else.
use std::collections::VecDeque;
fn drain_even(q: &mut VecDeque<i32>) -> Vec<i32> {
let mut out = Vec::new();
while let Some(&front) = q.front() {
if front % 2 == 0 {
out.push(q.pop_front().unwrap());
} else {
break;
}
}
out
}
fn main() {
let mut q = VecDeque::from([2, 4, 5, 6]);
println!("{:?}", drain_even(&mut q));
}What this demonstrates:
while let loops while pattern matchesbreak when condition changesif let for single-case branchlet else for required pattern (Rust 1.65+)if letif let Err(e) = result {
eprintln!("{e}");
}let elsefn head(s: &str) -> &str {
let Some((h, _)) = s.split_once(' ') else {
return s;
};
h
}else block must diverge (return, break, panic).
while letIdeal for consuming iterators of Option or Result until None/Err break pattern.
let else else block must diverge - Cannot fall through. Fix: return/break/panic!.if let - Binds move unless ref. Fix: if let Some(ref x).while let infinite if pattern always matches - Logic bug. Fix: Ensure iterator advances or state changes.if let - Hard to read. Fix: Use match or combinator methods.if let + else not full replacement for match - Only one positive arm ergonomic. Fix: match for many arms.| Alternative | Use When | Don't Use When |
|---|---|---|
match | Multiple arms | Single success path |
Option::map / and_then | Transform optional | Side effects in branches |
? on Option in fn | Propagate absence | In main without fn return |
unwrap_or / unwrap_or_else | Default value | Complex branch logic |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 16, 2026