Code Logo

Categorize with Range Patterns

Published at25 Jul 2026
Rust Functions Medium 0 views
Like0

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

Example 1
Input
95
Output
A
Explanation

95 is in 90..=100 range

Example 2
Input
50
Output
C
Explanation

50 is in 0..=69 range

Example 3
Input
100
Output
A
Explanation

100 is the upper bound

Example 4
Input
-5
Output
Invalid
Explanation

Negative is out of range

Example 5
Input
75
Output
B
Explanation

75 is in 70..=89 range

Algorithm Flow

Recommendation Algorithm Flow for Categorize with Range Patterns
Recommendation Algorithm Flow for Categorize with Range Patterns

Solution Approach

fn solution(score: i32) -> &'static str {
    match score {
        90..=100 => "A",
        70..=89 => "B",
        0..=69 => "C",
        _ => "Invalid",
    }
}

Best Answers

rust - Approach 1
fn solution(score: i32) -> &'static str {
    match score {
        90..=100 => "A",
        70..=89 => "B",
        0..=69 => "C",
        _ => "Invalid",
    }
}