Sub topic 3
if let, let else, while let, and matches!
Assume basic Rust syntax, ownership, borrowing, structs, and cargo. These pattern forms are shorter alternatives to match when you need only some cases.
Pattern-based control flow
if let runs code when one pattern matches:
if let Some(name) = user_name {
println!("Hello, {name}");
}let else requires a match and exits the current scope when it fails:
fn port(text: Option<&str>) -> Option<u16> {
let Some(text) = text else {
return None;
};
Some(text.parse().ok()?)
}while let repeats while a pattern matches:
let mut stack = vec![1, 2, 3];
while let Some(value) = stack.pop() {
println!("{value}");
}matches! turns a pattern test into a Boolean:
let is_lowercase = matches!('q', 'a'..='z');Result and the `?` operator
Result<T, E> represents success (Ok) or failure (Err). The ? operator returns an error immediately and unwraps success:
fn parse_port(text: &str) -> Result<u16, std::num::ParseIntError> {
Ok(text.parse()?)
}Moves, references, and binding modes
Matching by value can move data out of an enum. Match on a reference when the original value must remain usable:
enum Message {
Text(String),
Quit,
}
fn show(msg: &Message) {
match msg {
Message::Text(text) => println!("{text}"),
Message::Quit => println!("quit"),
}
}The pattern automatically borrows text because msg is borrowed.
Custom errors and conversions
An error enum can describe domain-specific failures. Implementing From lets ? convert lower-level errors:
enum ConfigError {
Missing,
Invalid(std::num::ParseIntError),
}
impl From<std::num::ParseIntError> for ConfigError {
fn from(error: std::num::ParseIntError) -> Self {
Self::Invalid(error)
}
}Modeling states and recursive values
Enums prevent invalid state combinations:
enum Connection {
Disconnected,
Connected { address: String },
}A recursive enum needs indirection because Box<T> stores its value on the heap:
enum Expr {
Number(i64),
Add(Box<Expr>, Box<Expr>),
}C-like enums and casting
A fieldless enum can have explicit discriminants:
#[derive(Debug)]
enum Level {
Low = 1,
High = 10,
}
fn main() {
println!("{}", Level::High as i32);
}The cast reads the integer discriminant. It does not make arbitrary integers valid Level values.
Exercise
Which form should you use to repeatedly remove matching values from a collection?
Show answer
Use while let, such as while let Some(value) = stack.pop().