Rust Fundamentals · 15 XP Pro
Custom error types
String errors are easy but vague. An enum lets each failure be its own
variant, which callers can match on and which can carry data.
#[derive(Debug, PartialEq)]
pub enum LoginError {
EmptyName,
TooShort(usize),
BadNumber(std::num::ParseIntError),
}
impl From<std::num::ParseIntError> for LoginError {
fn from(e: std::num::ParseIntError) -> Self {
LoginError::BadNumber(e)
}
}
With a From impl in place, ? converts the error automatically: a function
returning Result<_, LoginError> can use ? on a Result<_, ParseIntError>.
Your task
The starter already declares the enum. Everything must be pub, because the
tests use your crate as lesson.
- Write
impl From<std::num::ParseIntError> for AgeErrorreturningAgeError::NotANumber. - Write
pub fn parse_age(input: &str) -> Result<u32, AgeError>:- trim the input; if nothing is left, return
Err(AgeError::Empty) - parse as
u32using?(so"abc"and"-3"giveNotANumber) - if the age is above 150, return
Err(AgeError::TooOld(age)) - otherwise return
Ok(age)
- trim the input; if nothing is left, return