Advanced Pattern Matching
🎯 Python 3.10 introduced structural pattern matching:
match command:
case {"action": "move", "x": x, "y": y}:
print(f"Moving to {x}, {y}")
case {"action": "quit"}:
print("Goodbye")
Rust's match goes further with features you'll use constantly: ranges, multiple patterns, guards, destructuring, and exhaustiveness checking. This exercise drills all of them.
Ranges and multiple patterns
match score {
90..=100 => "A", // range pattern
75..=89 | 70..=74 => "B/C", // multiple patterns with |
_ => "below", // catch-all
}
Python's match doesn't support ranges directly — you'd use case x if 90 <= x <= 100. Rust makes it first-class syntax.
Guards
Guards add conditions to patterns:
match age {
n if n >= 18 => "adult",
13..=17 => "teen",
_ => "child",
}
Python has guards too (case x if x >= 18), so this concept transfers directly.
Destructuring
Rust can destructure tuples, structs, and enums in match arms:
match (width, height) {
(w, h) if w == h => w * w, // destructure tuple + guard
(w, h) => w * h,
}
Enum destructuring
Enums with data are destructured to extract their contents:
enum Command {
Say(String),
Resize { w: u32, h: u32 },
Exit,
}
match cmd {
Command::Say(s) if !s.is_empty() => s,
Command::Say(_) => "(nothing)".into(),
Command::Resize { w, h } => format!("{w}x{h}"),
Command::Exit => "done".into(),
}
Each variant can have its own guard. The compiler ensures all variants are handled.
Login to see the full task and start coding.
This is a premium exercise
Log in to unlock the full exercise and start coding.
Login to access this exercise