Sub topic 9
if let, while let, and let-else
This chapter assumes you know match, Option, and Result, and that you can write functions and loops. A match must cover every case. That is often more than you need when you care about only one pattern. Rust has three shorter forms for that situation.
if let
if let runs a block when a value matches one pattern. It can have an else branch for everything else.
fn main() {
let input = "42";
if let Ok(n) = input.parse::<i32>() {
println!("parsed {n}");
} else {
println!("not a number");
}
}The pattern Ok(n) binds n only inside the first block. This is the same as a match with one arm for the pattern and a _ arm for the rest. Unlike match, the compiler does not check that you handled every case. That is the trade-off for brevity.
Like if, an if let is an expression. If both branches produce a value, they must have the same type.
while let
while let repeats as long as a pattern keeps matching. It is common with methods that return Option, such as pop.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("{top}");
}
}pop returns Some(value) while the vector has items and None when it is empty. The loop ends at the first None. This prints 3, 2, 1.
let-else
let-else handles the case where a pattern must match for the rest of the function to make sense. If the pattern matches, its bindings are available after the statement. If it does not, the else block runs.
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(" "));
}The program prints 5, then 0. The else block must diverge. It has to leave the current flow with return, break, continue, or a panic!. The compiler rejects an else block that falls through, because word would then be unbound.
Compare the if let version of the same logic. It nests the main work one level deeper:
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"));
}This is fine for two lines. With several checks in a row, let-else keeps the main path at one indentation level.
Choosing between them
Common errors
- Scope mix-up. Bindings from
if letexist only inside its block. Bindings fromlet-elseexist in the surrounding scope. - A non-diverging else. An
elseblock inlet-elsethat ends with a plain value fails to compile. Addreturn,continue, orbreak. - Refutable pattern in a plain let.
let Some(x) = opt;is an error because the pattern can fail. Uselet-elseorif let. - Infinite while let. If the expression never produces a non-matching value, the loop never ends.
while let Some(x) = v.first()loops forever becausefirstdoes not remove anything.
Exercise
Write a function parse_or_zero(s: &str) -> i32 that returns the parsed integer, or 0 if parsing fails. Use let-else.
Show answer
fn parseorzero(s: &str) -> i32 {
let Ok(n) = s.trim().parse::<i32>() else {
return 0;
};
n
}
The else block returns, so it diverges. After the statement, n is bound in the function scope.
Exercise
What does this loop print? let mut v = vec![10, 20]; while let Some(x) = v.pop() { println!("{x}"); }
Show answer
It prints 20, then 10. pop removes from the end. When the vector is empty, pop returns None and the loop stops.