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
@ bindings capture values. Guards add conditions.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the patterns category to build a complete understanding of this topic.