intermediateFlow Control
Match Guards
Add conditions to match arms with guards.
Match Guards
Add conditions to match arms with guards.
Difficulty
Intermediate
Code
rust
fn main() {
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("equal"),
(x, y) if x + y == 0 => println!("sum to zero"),
(x, _) if x % 2 == 1 => println!("first is odd"),
_ => println!("no match"),
}
}Explanation
This example demonstrates how to use match guards 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 flow-control category to build a complete understanding of this topic.