Code Logo

Categorize with match

Published at25 Jul 2026
Rust Functions Easy 0 views
Like0

Write a Rust function that uses a match expression to categorize an integer as "positive", "negative", or "zero". The match expression is Rust's powerful pattern matching construct that allows branching based on the structure and value of data.

Rust's match is exhaustive, meaning every possible value must be covered. For integer matching, you can use literal patterns (0), range patterns (1..=i32::MAX), and the wildcard pattern (_) to catch remaining cases. The compiler verifies exhaustiveness at compile time, preventing forgotten cases.

Unlike switch statements in other languages, Rust's match does not fall through to the next arm. Each arm is independent, and the first matching arm is executed. The match expression returns a value, making it an expression rather than a statement. This allows assigning the result directly to a variable.

Time complexity is O(1) as match on simple integer patterns compiles to efficient conditional branches. Space complexity is O(1). The match expression is zero-cost and often optimizes better than equivalent if-else chains.

Edge cases include the boundary between zero and positive numbers, negative numbers, very large positive and negative values, and ensuring the wildcard _ pattern catches all unlisted cases.

Example Input & Output

Example 1
Input
100
Output
positive
Explanation

100 is positive

Example 2
Input
0
Output
zero
Explanation

0 is zero

Example 3
Input
-1
Output
negative
Explanation

-1 is negative

Example 4
Input
5
Output
positive
Explanation

5 is positive

Example 5
Input
-3
Output
negative
Explanation

-3 is negative

Algorithm Flow

Recommendation Algorithm Flow for Categorize with match
Recommendation Algorithm Flow for Categorize with match

Solution Approach

Match an integer value against multiple patterns using Rust's match expression. Match arms consist of patterns and expressions, separated by =>. The _ wildcard handles all remaining cases.

fn solution(n: i32) -> &'static str { match n { 1 => "one", 2 | 3 => "two or three", 4..=10 => "four to ten", _ => "other" } }

Match patterns support literals, ranges (..=), multiple values (|), wildcards (_), and guards (if). Exhaustive matching requires covering all possible values.

Time O(1), Space O(1).

Best Answers

rust - Approach 1
fn solution(n: i32) -> &'static str {
    match n {
        0 => "zero",
        n if n > 0 => "positive",
        _ => "negative",
    }
}