if let and let else
match requires an arm for every variant. But often you care about only one.
Back to the sorting machine. Imagine the post office is looking only for packages and sends everything else to a common crate. There is no point in a bin for every sticker: one "packages" bin and one "everything else" crate are enough. With match it looks like this: an arm Some(q) and an arm _ => {} that does nothing. Rust lets you write the same thing shorter:
fn divide(a: i32, b: i32) -> Option<i32> {
if b == 0 { None } else { Some(a / b) }
}
fn main() {
if let Some(q) = divide(10, 2) {
println!("{q}"); // 5
}
if let Some(q) = divide(1, 0) {
println!("{q}");
} else {
println!("no result"); // no result
}
}Let's walk through the example line by line:
divide(10, 2)returnsSome(5). The patternSome(q)fits,qgets5, and the block prints5.divide(1, 0)returnsNone. The pattern does not fit, and the first block is skipped.- The
elseblock runs and printsno result.
if let: one pattern
if let checks one value against one pattern. The form has these parts:
if letare the keywords;Some(q)is the pattern, the same as in amatcharm;=and the value being checked;- the block in curly braces runs if the pattern fits;
elsewith a block is optional and covers all other cases.
The variable q is visible only inside the first block. The pattern can be anything: if let Parcel::Package(kg) = p checks for a package and takes out its weight.
You pay for brevity with exhaustiveness. if let does not check that every variant is handled: whatever does not fit silently goes to else or is skipped.
let else: take it out or leave
Sometimes it is the other way around: without the value there is nothing more to do, and the function must end right away. For that there is let else: it takes the value out of the pattern. If the pattern does not fit, it runs the else block, which must leave the function or the loop.
fn half_price(price: Option<u32>) -> u32 {
let Some(p) = price else {
return 0;
};
p / 2
}
fn main() {
println!("{} {}", half_price(Some(80)), half_price(None)); // 40 0
}- For
Some(80)the pattern fits, andpgets80. pis visible until the end of the function, not only inside a block as withif let. The function returns40.- For
Nonethe pattern does not fit, andelserunsreturn 0.
The else block must leave: with return, or in a loop with break or continue. Without else the line does not compile: let Some(p) = price; gives error[E0005]: refutable pattern in local binding. A plain let accepts only patterns that always fit, and Some(p) may not fit.
Here the machine picture falls short. A package that missed the bin still lies in the common crate. But after let else an empty value has nowhere to go: the function ends, and the code below works only with a real p.
Which to choose
Interviewers like to ask this: "When are if let and let else better than match?" The answer:
matchwhen every variant matters: the compiler checks that none is forgotten;if letwhen you need one variant and the rest can be skipped;let elsewhen the function has nothing more to do without the value;- neither
if letnorlet elsechecks exhaustiveness.
Common mistake
The else block holds a fallback value instead of leaving:
fn half_price(price: Option<u32>) -> u32 {
let Some(p) = price else { 0 }; // ✗
p / 2
}error[E0308]: `else` clause of `let...else` does not divergeThe program does not compile. The else block gives 0 here, but the code below still expects p, and there is none. So else must leave the function: the fix is else { return 0; }.
Key points
if let Some(q) = x { … } else { … }handles one variant; the rest go toelse.let Some(p) = x else { return …; };takes the value out for the rest of the function, or leaves.- The
elseblock oflet elsemust leave withreturn,breakorcontinue(otherwise E0308). if letandlet elseare shorter thanmatch, but do not check that every variant is handled.