Sub topic 1
Patterns and match: the starting point
Prerequisites
Assume you know basic Rust functions, let bindings, println!, Option, Result, match, patterns, and ownership basics.
A pattern describes a shape that a value may have. The match expression compares a value with patterns from top to bottom. The first matching arm runs, and every possible value must be covered.
fn describe(value: Option<i32>) -> String {
match value {
Some(number) => format!("number: {number}"),
None => String::from("no number"),
}
}
fn main() {
println!("{}", describe(Some(7)));
println!("{}", describe(None));
}Refutable versus irrefutable patterns
An irrefutable pattern always matches. A simple variable such as number is irrefutable because it can bind any value.
A refutable pattern may fail. Some(number) is refutable because an Option<i32> might instead be None.
| Pattern | Kind | Example |
|---|---|---|
| `value` | Irrefutable | `let value = 7;` |
| `Some(value)` | Refutable | `match option { Some(value) => ... }` |
| `Some(value)` in `let` | Invalid | It might not match |
Rust requires constructs such as ordinary let to use irrefutable patterns. match, if let, and while let are designed for refutable patterns.
`if let`: matching one pattern
if let runs a block only when its pattern matches. It is shorter than a match with one important arm and an ignored arm.
fn main() {
let config_port: Option<u16> = Some(8080);
if let Some(port) = config_port {
println!("listening on {port}");
}
}The binding port exists only inside the block. If the value is None, the block is skipped.
Adding `else` and `else if let`
An else handles every value that fails the pattern. The binding from the pattern remains limited to its matching block.
fn main() {
let port: Option<u16> = None;
if let Some(port) = port {
println!("listening on {port}");
} else {
println!("using default port");
}
}For several selected cases, chain conditions with else if let. If none matches, the final else runs.
fn describe(value: Option<i32>) {
if let Some(0) = value {
println!("zero");
} else if let Some(number) = value {
println!("nonzero: {number}");
} else {
println!("missing");
}
}Exercise
Why can Some(value) be used in if let but not as the pattern of an ordinary let binding?
Show answer
Some(value) is refutable: it can fail to match when the value is None. An ordinary let requires an irrefutable pattern.