snippetrustModeratepending
Rust pattern matching advanced features
Viewed 0 times
matchpatterndestructuringguardbindingif-let
Problem
Rust match expressions have powerful features beyond simple value matching that are underutilized.
Solution
Advanced match patterns in Rust:
// Guards
match x {
n if n < 0 => println!("negative"),
0 => println!("zero"),
n if n > 100 => println!("large"),
n => println!("other: {n}"),
}
// Destructuring structs
match point {
Point { x: 0, y } => println!("on y-axis at {y}"),
Point { x, y: 0 } => println!("on x-axis at {x}"),
Point { x, y } => println!("({x}, {y})"),
}
// OR patterns
match status {
200 | 201 | 204 => println!("success"),
400..=499 => println!("client error"),
500..=599 => println!("server error"),
_ => println!("other"),
}
// Binding with @
match age {
n @ 0..=12 => println!("child aged {n}"),
n @ 13..=19 => println!("teenager aged {n}"),
n => println!("adult aged {n}"),
}
// Nested destructuring
match msg {
Message::Move { x, y } if x > 0 => handle_right(x, y),
Message::Write(text) if !text.is_empty() => print(text),
Message::Quit => return,
_ => (), // Ignore other cases
}
// if let for single pattern
if let Some(value) = optional {
use_value(value);
}
// let else (Rust 1.65+)
let Some(value) = optional else { return; };
// Guards
match x {
n if n < 0 => println!("negative"),
0 => println!("zero"),
n if n > 100 => println!("large"),
n => println!("other: {n}"),
}
// Destructuring structs
match point {
Point { x: 0, y } => println!("on y-axis at {y}"),
Point { x, y: 0 } => println!("on x-axis at {x}"),
Point { x, y } => println!("({x}, {y})"),
}
// OR patterns
match status {
200 | 201 | 204 => println!("success"),
400..=499 => println!("client error"),
500..=599 => println!("server error"),
_ => println!("other"),
}
// Binding with @
match age {
n @ 0..=12 => println!("child aged {n}"),
n @ 13..=19 => println!("teenager aged {n}"),
n => println!("adult aged {n}"),
}
// Nested destructuring
match msg {
Message::Move { x, y } if x > 0 => handle_right(x, y),
Message::Write(text) if !text.is_empty() => print(text),
Message::Quit => return,
_ => (), // Ignore other cases
}
// if let for single pattern
if let Some(value) = optional {
use_value(value);
}
// let else (Rust 1.65+)
let Some(value) = optional else { return; };
Why
Rust's match is exhaustive and compiler-checked. Advanced patterns reduce nested if/else chains to concise, readable code.
Revisions (0)
No revisions yet.