Rust Fundamentals · 15 XP Pro
Match expressions
match compares a value against a list of patterns and runs the first arm that
fits. It is an expression, so the whole match has a value. The compiler insists the
match is exhaustive: every possible value must be covered, or the code does not
compile.
fn label(n: i32) -> &'static str {
match n {
0 => "zero",
1 | 2 | 3 => "few",
4..=9 => "several",
x if x < 0 => "negative",
_ => "many",
}
}
Things to notice:
|combines patterns anda..=bmatches an inclusive range.x if x < 0is a guard: the arm applies only if the extra condition is true. Herexis also a binding, a name for the matched value._matches anything and is the usual last arm. Arms are checked top to bottom, so order matters.
Patterns can take apart tuples too, binding pieces as they go:
match (a, b) {
(0, _) => "first is zero",
(_, y) => if y > 0 { "positive" } else { "other" },
}
Your task
The tests use everything below, so all of it must be pub.
pub enum Coin { Penny, Nickel, Dime, Quarter }(keep the derive line from the starter) andpub fn cents(c: Coin) -> u32returning 1, 5, 10 and 25.pub fn classify(n: i32) -> &'static str:"zero"for 0,"negative"for anything below 0,"small"for 1 to 9, and"large"otherwise.pub fn locate(p: (i32, i32)) -> String:(0, 0)gives"origin",(x, 0)gives"x axis at {x}",(0, y)gives"y axis at {y}", and any other point gives"({x}, {y})", for example"(3, -4)".