Patterns work as in Rust. describe matches on enum variants and their fields: a literal field (dx: 0) only matches that value, .. ignores the remaining fields, and an if guard adds a condition to an arm.
classify matches integer ranges. x @ 10..=99 binds the value while also testing it.
slices matches on the length and contents of a slice, and [first, .., last] binds the first and last elements.
if let runs code only when a pattern matches. let ... else binds the pattern’s variables for the rest of the function, and its else block must leave the function.
03_pattern_matching.ox
// match, if let, let-else and pattern forms.
enum Command {
Move { dx: i32, dy: i32 },
Say(String),
Quit,
}
fn describe(cmd: &Command) -> String {
match cmd {
Command::Move { dx: 0, dy: 0 } => "stay".to_string(),
Command::Move { dx, dy } if dx.abs() > 10 || dy.abs() > 10 => "dash".to_string(),
Command::Move { .. } => "step".to_string(),
Command::Say(text) => format!("say {text}"),
Command::Quit => "quit".to_string(),
}
}
fn classify(n: u32) -> &'static str {
match n {
0 => "zero",
1..=9 => "digit",
x @ 10..=99 if x % 10 == 0 => "round",
10..=99 => "two digits",
_ => "large",
}
}
fn slices(values: &[i32]) -> i32 {
match values {
[] => 0,
[only] => *only,
[first, .., last] => first + last,
}
}
fn optional(maybe: Option<i32>) -> i32 {
if let Some(v) = maybe {
return v;
}
let Some(v) = maybe else {
return -1;
};
v
}
fn nested(pair: (Option<u8>, Result<u8, String>)) {
match pair {
(Some(a), Ok(b)) => {}
(None, Err(ref msg)) => {}
_ => {}
}
}