Categorize with match
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
100 is positive
0 is zero
-1 is negative
5 is positive
-3 is negative
Algorithm Flow

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.
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
fn solution(n: i32) -> &'static str {
match n {
0 => "zero",
n if n > 0 => "positive",
_ => "negative",
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
