Sub topic 3
Pattern-Based Control Flow and Advanced Functions
Prerequisites: basic Rust syntax, cargo, primitive types, variables, and mutability. This chapter assumes you understand ownership at a basic level.
`if let`, `while let`, and `let-else`
Use if let when you care about one pattern and want to ignore the others. A pattern describes a value's shape.
fn main() {
let value = Some(7);
if let Some(number) = value {
println!("{number}");
}
}while let repeats while a value matches a pattern. This example removes items from a vector until it is empty.
fn main() {
let mut values = vec![3, 2, 1];
while let Some(value) = values.pop() {
println!("{value}");
}
}let-else binds a pattern or leaves the current control-flow path. The else block must diverge, meaning it cannot continue normally.
fn first_word(s: &str) -> &str {
let Some(word) = s.split_whitespace().next() else {
return "";
};
word
}Passing references and returning early
A reference borrows a value without taking ownership. Use &mut when a function must change the borrowed value.
fn add_suffix(text: &mut String) {
text.push_str("!");
}
fn main() {
let mut message = String::from("Hi");
add_suffix(&mut message);
println!("{message}");
}The ? operator returns an error immediately when a Result is Err. Otherwise, it extracts the successful value.
fn double(input: &str) -> Result<i32, std::num::ParseIntError> {
let number: i32 = input.parse()?;
Ok(number * 2)
}Recursion
Recursion is a function calling itself. Every recursive function needs a base case.
fn factorial(n: u64) -> u64 {
if n <= 1 { 1 } else { n * factorial(n - 1) }
}Closures and function pointers
A closure is an unnamed function that can capture values. A generic Fn parameter accepts closures and named functions.
fn apply<F: Fn(i32) -> i32>(function: F, value: i32) -> i32 {
function(value)
}
fn main() {
println!("{}", apply(|x| x + 1, 4));
}Diverging functions
A function returning ! never returns normally. panic!, an infinite loop, and process termination are examples. Diverging expressions can fit where any type is expected.
fn fail(message: &str) -> ! {
panic!("{message}");
}Exercise
Which construct is appropriate when a missing value should immediately return from the current function?
Show answer
let-else, with an else block containing return, break, continue, or another diverging expression.