Let's improve previous example a little bit by returning a custom error type instead of a plain string. This will allow us to define specific error types and provide more structured error handling.
Your Task
The logic of the function remains the same as the previous challenge, but the returned error type is what you need to change.
-
Define an enum
ParsePercentageErrorwith the following variants:InvalidInput: for inputs that cannot be parsed as numbers.OutOfRange: for numbers that are not in the range 0-100.
-
Implement the
Errortrait forParsePercentageError. Use thestd::error::Errortrait and provide human-readable descriptions for each error. -
Update the
parse_percentagefunction to:- Return
Ok(u8)if the input is a valid percentage (between 0 and 100). - Return
Err(ParsePercentageError::OutOfRange)if the number is out of range. - Return
Err(ParsePercentageError::InvalidInput)if the input is not a valid number.
- Return
Hints
<details> <summary>Click here to reveal hints</summary>- The
std::error::Errortrait requires implementing theDisplayandDebugtraits. You can deriveDebugby#[derive(Debug)]and implementDisplaymanually. - Use the
std::fmtmodule to implementDisplayfor the error enum, which is required for theErrortrait.
// 1. Finish the definitionpub enum ParsePercentageError// 2. Implement the `Error` traitpub fn parse_percentage(input: &str) -> Result<u8, ParsePercentageError> {// 3. Implement this function}// Example usagepub fn main() {let result = parse_percentage("50");println!("{:?}", result); // Should print: Ok(50)let result = parse_percentage("101");println!("{:?}", result); // Should print: Err(ParsePercentageError::OutOfRange)let result = parse_percentage("abc");println!("{:?}", result); // Should print: Err(ParsePercentageError::InvalidInput)}