fn main() {
let x = 7i32;
// Basic match - exhaustive
let desc = match x {
1 => "one",
2 | 3 => "two or three",
4..=9 => "four through nine",
n if n < 0 => "negative",
_ => "other",
};
println!("{}: {}", x, desc);
// @ binding: test and capture
let msg = match x {
n @ 1..=9 => format!("single digit: {}", n),
n => format!("multi digit: {}", n),
};
println!("{}", msg);
// Matching tuples
let point = (0, 7);
match point {
(0, y) => println!("on y-axis at y={}", y),
(x, 0) => println!("on x-axis at x={}", x),
(x, y) => println!("at ({}, {})", x, y),
}
// Matching with structs
struct Point { x: i32, y: i32 }
let p = Point { x: 5, y: 0 };
match p {
Point { x, y: 0 } => println!("On x-axis at {}", x),
Point { x: 0, y } => println!("On y-axis at {}", y),
Point { x, y } => println!("({}, {})", x, y),
}
// Guards
let pair = (2, -2);
match pair {
(x, y) if x == y => println!("Equal"),
(x, y) if x + y == 0 => println!("Sum zero"),
(x, _) if x > 0 => println!("First positive"),
_ => println!("Other"),
}
}