Rust Match Arms: Categorize and Process Data
In Rust, the match control flow construct is a powerful way to handle different possibilities for a given value. It's essential for pattern matching and writing robust, readable code. This challenge will test your ability to effectively use match arms to categorize and process data based on its structure and content.
Problem Description
You are tasked with creating a Rust function that takes a generic Item (which can be an enum or a struct) and performs different actions based on the type and specific values of the Item. You will implement a match expression with multiple arms to handle various cases.
Your function should:
- Accept an
Itemas input. - Use a
matchstatement to inspect theItem. - Implement distinct logic for each defined
Itemvariant. - Return a
Stringdescribing the action taken or the characteristic of theItem.
Consider the following Item definition:
enum Item {
Number(i32),
Text(String),
Boolean(bool),
Coordinate { x: i32, y: i32 },
Empty,
}
Your match arms should handle:
Item::Numberwith values less than 0, between 0 and 100 (inclusive), and greater than 100.Item::Textwith empty strings and non-empty strings.Item::Booleanspecifically fortrueandfalse.Item::Coordinatewherexis equal toy, and wherexis not equal toy.Item::Empty.
Examples
Example 1:
Input: Item::Number(-5)
Output: "Received a negative number: -5"
Explanation: The input is an `Item::Number` with a value less than 0.
Example 2:
Input: Item::Text(String::from("Hello, Rust!"))
Output: "Received a non-empty text: Hello, Rust!"
Explanation: The input is an `Item::Text` containing a string with characters.
Example 3:
Input: Item::Coordinate { x: 10, y: 10 }
Output: "Received a coordinate with equal x and y values: (10, 10)"
Explanation: The input is an `Item::Coordinate` where x equals y.
Example 4:
Input: Item::Empty
Output: "Received an empty item."
Explanation: The input is the `Item::Empty` variant.
Example 5:
Input: Item::Number(50)
Output: "Received a non-negative number up to 100: 50"
Explanation: The input is an `Item::Number` with a value between 0 and 100 inclusive.
Example 6:
Input: Item::Text(String::new())
Output: "Received an empty text string."
Explanation: The input is an `Item::Text` with an empty string.
Constraints
- The function must be written in Rust.
- The provided
Itemenum definition should be used. - All variants of the
Itemenum must be handled within thematchstatement. - The function should return a
String.
Notes
- Pay close attention to destructuring in your
matcharms to extract inner values from enum variants. - Rust's pattern matching allows for guards (
if condition) to add further conditions to a match arm. - Think about how to represent the output strings clearly for each distinct case.
- You'll need to define the
Itemenum yourself in your solution.