Sub topic 2
`while let`, `let else`, and Avoiding Nested Matches
Assume basic Rust syntax, Option and Result, match, and ownership and borrowing.
`while let`: looping while a pattern matches
while let repeats a block while a value matches a pattern. It is useful when an operation produces Some until its input is exhausted.
fn main() {
let mut stack = vec![1, 2, 3];
while let Some(top) = stack.pop() {
println!("popped {top}");
}
}Each call to pop returns Some(value) while the vector contains an item. When the vector is empty, pop returns None, so the loop stops.
Bindings, shadowing, and moves
A name introduced by a pattern is scoped to the matching branch or loop body:
let input = Some(String::from("ready"));
if let Some(input) = input {
println!("{input}");
}The inner input shadows the outer name. Because String is not Copy, this pattern moves the string out of the Option. Use a reference when the original value must remain usable:
let input = Some(String::from("ready"));
if let Some(input) = input.as_ref() {
println!("{input}");
}
println!("{input:?}");`let else`: unwrap or leave early
let else requires a pattern to match. On success, its bindings remain available in the surrounding scope.
fn parse_port(input: &str) -> Result<u16, String> {
let Ok(port) = input.trim().parse::<u16>() else {
return Err(format!("invalid port: {input}"));
};
Ok(port)
}
fn main() {
println!("{:?}", parse_port(" 8080 "));
println!("{:?}", parse_port("abc"));
}Why the `else` block must diverge
The else block must diverge: it must transfer control away from the current point. return, break, continue, and panic! can do this. Rust requires this because port must exist after the statement.
The nesting problem
Chained checks can create rightward drift:
if let Some(text) = first {
if let Ok(n) = text.parse::<i32>() {
if n > 0 {
return format!("positive number {n}");
}
}
}Each condition adds indentation. Let chains, covered next, combine pattern matches and boolean conditions with &&, keeping the successful path flatter.
Exercise
Why does while let Some(value) = stack.pop() stop when the stack is empty?
Show answer
pop returns None, which does not match Some(value), so the loop exits.