advancedPatterns
Pattern Guards and Bindings
Use @ bindings and match guards in patterns.
Pattern Guards and Bindings
Use @ bindings and match guards in patterns.
Difficulty
Advanced
Code
rust
fn main() {
let x = 5;
match x {
n @ 1..=5 => println!("1-5: {}", n),
n @ 6..=10 => println!("6-10: {}", n),
n => println!("other: {}", n),
}
let msg = Some(42);
match msg {
Some(n) if n > 100 => println!("big: {}", n),
Some(n) => println!("small: {}", n),
None => println!("none"),
}
}Explanation
This example demonstrates how to use pattern guards and bindings in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the patterns category to build a complete understanding of this topic.