Structs, Enums, and Matching
Pattern Matching
Destructuring and Guards
Patterns can destructure tuples and add if guards, so one match expresses several conditions.
Program
Play the program to classify a point with a match guard.
pattern_match.rs
Replay: real traced execution (multi-file project)
fn main() {
let point = (2, -3);
let label = match point {
(0, 0) => "origin",
(x, _) if x > 0 => "right",
_ => "other",
};
println!("{label}");
}
point ← (2, -3), label ← "right"
1fn main() {2 let poin→ (2, -3)t = (2, -3);3 let labe→ "right"l = match poin(2, -3)t {4 (0, 0) => "origin",5 (x, _) if x > 0 => "right",6 _ => "other",7 };8 println!("{label}");9}outputright
Follow the Trace
pointstarts as(2, -3).- The
(0, 0)arm does not match. - The
(x, _) if x > 0arm matches becausexis2. labelbecomesright.- The program prints
right. | trace point | value | | --- | --- | | point |(2, -3)| | matched arm |(x, _) if x > 0| |x| 2 | | label | right | | stdout |right|
destructuring
`(x, _)` pulls the first tuple field into `x`.
match guard
`if x > 0` adds a condition to an arm.
order
Arms are tried top to bottom; the first fit wins.
Exercise: pattern_match.rs
Reproduce the output right, then trace which match arm wins for point (2, -3).