Categorize with Range Patterns
Write a Rust function that uses range patterns in a match expression to categorize a number into letter grades. Use the ..= syntax for inclusive range patterns: 90..=100 returns "A", 70..=89 returns "B", 0..=69 returns "C". Any other value returns "Invalid".
Rust's match arms support range patterns using the ..= (inclusive) and .. (exclusive) syntax. This allows matching against a range of numeric values without writing multiple arms with comparison operators. Range patterns are part of Rust's powerful pattern matching system, which also includes destructuring, guards, and binding.
Range patterns are compiled to efficient bounds checks, not linear comparisons. The compiler optimizes sequential range patterns into a binary search or jump table when possible. This makes match expressions with many range arms both readable and performant, unlike chains of if-else statements.
Time complexity is O(1) as range matching compiles to efficient bounds comparisons. Space complexity is O(1). The match expression is exhaustive when combined with the wildcard _ pattern, ensuring all possible values are handled at compile time.
Edge cases include exact boundary values (0, 69, 70, 89, 90, 100), negative numbers (fall to the wildcard arm), and values exactly at the transition points between ranges. The inclusive ..= syntax ensures boundary values are handled correctly.
Example Input & Output
95 is in 90..=100 range
50 is in 0..=69 range
100 is the upper bound
Negative is out of range
75 is in 70..=89 range
Algorithm Flow

Solution Approach
Best Answers
fn solution(score: i32) -> &'static str {
match score {
90..=100 => "A",
70..=89 => "B",
0..=69 => "C",
_ => "Invalid",
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
