Sub topic 9
if let, while let, and let-else
This chapter covers three pattern-based forms of control flow: if let, while let, and let-else. They let you match one pattern without writing a full match. I assume you know match, Option, Result, let mut, and how to run a program with cargo.
Why these forms exist
A match must cover every possible value. Often you care about only one case, such as "there is a value" in an Option. Writing a match with an empty _ => {} arm works, but it is noisy.
fn main() {
let name: Option<&str> = Some("Ferris");
match name {
Some(n) => println!("hello, {n}"),
_ => {}
}
}The three forms below remove that noise. Each one tests a pattern against a value. If the pattern matches, it binds names. If it doesn't, each form does something different.
| Form | If the pattern matches | If it does not match |
|---|---|---|
| `if let` | Runs the block, with the bindings in scope | Skips the block, or runs `else` |
| `while let` | Runs the loop body, then tests again | Ends the loop |
| `let-else` | Bindings stay in scope after the statement | Runs an `else` block that must diverge |
Branching with if let
if let PATTERN = EXPRESSION { ... } runs the block only when the expression matches the pattern. Names bound in the pattern exist only inside that block.
fn main() {
let name: Option<&str> = Some("Ferris");
if let Some(n) = name {
println!("hello, {n}");
}
}Note that the pattern is on the left of =, which is the reverse of what a match scrutinee looks like. Read it as "if name fits the shape Some(n), then...".
Adding else
You can attach else and chain else if or else if let. The branches can mix plain conditions and pattern tests.
fn describe(input: Option<i32>, fallback: bool) -> String {
if let Some(n) = input {
format!("got {n}")
} else if fallback {
String::from("using fallback")
} else {
String::from("nothing")
}
}
fn main() {
println!("{}", describe(Some(3), false));
println!("{}", describe(None, true));
println!("{}", describe(None, false));
}Like a plain if, an if let is an expression. When you use its value, every branch must produce the same type, and an if let without else can only have the type ().
The trade-off: exhaustiveness is gone
A match makes the compiler check that you handled every case. if let does not. If you later add a variant to an enum, an if let will silently ignore it, while a match would fail to compile and point you to the place to update.
enum Command {
Start,
Stop,
Pause,
}
fn run(cmd: Command) {
if let Command::Start = cmd {
println!("starting");
}
// Stop and Pause are ignored without any warning.
}
fn main() {
run(Command::Start);
run(Command::Stop);
run(Command::Pause);
}Use if let when ignoring the other cases is truly intended. Use match when each case deserves a decision.
Borrowing and moving in patterns
A pattern binding can move the value out of the thing you match. If you match on a String inside an Option by value, the option is partly moved and you can't use it afterwards. Matching on a reference avoids that.
fn main() {
let title: Option<String> = Some(String::from("Rust"));
if let Some(t) = &title {
println!("length {}", t.len());
}
println!("{:?}", title);
}Here &title makes t a &String, so title is still usable on the last line. Without the &, t would take ownership of the string and the final println! would not compile.
Looping with while let
while let PATTERN = EXPRESSION { ... } evaluates the expression before each iteration. The loop continues as long as the pattern matches, and ends the first time it does not. It suits sources that eventually run out, such as a stack or an iterator.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("{top}");
}
}Vec::pop returns Some(value) while items remain and None when the vector is empty. The loop therefore prints 3, 2, 1 and stops.
Driving an iterator by hand
You can also call next on an iterator yourself. This is useful when the loop body needs to take extra items from the same iterator.
fn main() {
let mut tokens = "10 20 add 30".split_whitespace();
while let Some(tok) = tokens.next() {
match tok.parse::<i32>() {
Ok(n) => println!("number {n}"),
Err(_) => println!("word {tok}"),
}
}
}For a plain walk over a collection, a for loop is simpler. Prefer while let when the loop must change the source it reads from, as pop does, or when you need to call next more than once per iteration.
Pattern matching can be refutable or irrefutable
A pattern that can never fail, such as x or (a, b), is irrefutable. if let and while let expect a refutable pattern, one that can fail. With an irrefutable pattern, the compiler warns that the pattern always matches. With while let, that would also mean an endless loop.
Early exit with let-else
let PATTERN = EXPRESSION else { ... }; binds the pattern's names in the surrounding scope. If the pattern does not match, the else block runs. That block must diverge: it has to end with return, break, continue, panic!, or another expression of the never type !.
fn first_word_len(s: &str) -> usize {
let Some(word) = s.split_whitespace().next() else {
return 0;
};
word.len()
}
fn main() {
println!("{}", first_word_len(" hello world"));
println!("{}", first_word_len(" "));
}This prints 5, then 0. After the let, word is a plain &str, not an Option. The "happy path" stays at the left margin instead of being nested inside an if let.
Compare the same logic written with if let:
fn first_word_len_nested(s: &str) -> usize {
if let Some(word) = s.split_whitespace().next() {
word.len()
} else {
0
}
}
fn main() {
println!("{}", first_word_len_nested(" hello world"));
}Both are correct. The nested form grows a level of indentation for each check, so a function with three or four preconditions becomes hard to read. let-else keeps them flat.
Using let-else inside loops
Because continue and break diverge, let-else works well for skipping bad items.
fn main() {
let lines = ["3", "x", "7", ""];
let mut sum = 0;
for line in lines {
let Ok(n) = line.parse::<i32>() else {
continue;
};
sum += n;
}
println!("{sum}");
}This prints 10. Lines that fail to parse are skipped.
Rules and gotchas
- The
elseblock must not fall through. If it can reach its end, the compiler reports an error. - The pattern must be refutable. An irrefutable pattern gives a warning because the
elsecan never run. - The expression on the right cannot end in a
}that would makeelseambiguous, such as a bareif ... { } else { }. Wrap it in parentheses or put it in a variable first. - Bindings live in the enclosing scope, so they can shadow earlier names. This is often what you want, as in
let Some(x) = x else { return };.
Choosing between the forms
A short rule of thumb follows the diagram.
- Use
matchwhen more than one case needs its own behavior, or when you want the compiler to flag new variants. - Use
if letwhen only the matching case has work to do. - Use
while letwhen you repeat work until a source runs dry. - Use
let-elsewhen a mismatch means the rest of the block makes no sense and you want the bound names afterwards.
Exercises
Exercise
What does this program print, and why? fn main() { let mut items = vec![1, 2, 3]; while let Some(x) = items.pop() { if x == 2 { break; } println!("{x}"); } println!("{:?}", items); }
Show answer
It prints "3", then "[1]". The first pop yields 3, which is printed. The second pop yields 2, which triggers break before printing. The element 2 has already been removed, so the vector holds only [1].
Exercise
Rewrite this function with let-else so the main logic is not nested. fn double_first(v: &[i32]) -> i32 { if let Some(first) = v.first() { first * 2 } else { -1 } }
Show answer
fn double_first(v: &[i32]) -> i32 {
let Some(first) = v.first() else {
return -1;
};
first * 2
}
The else block returns, so it diverges. After the let statement, first is a &i32 available for the rest of the function.
Exercise
Why can an if let hide a bug that a match would catch when you add a new enum variant?
Show answer
A match must be exhaustive, so adding a variant makes it fail to compile until you handle the new case. An if let only tests one pattern and silently ignores everything else, so the new variant falls through with no error or warning.