diff --git a/exercises/13_error_handling/errors6.rs b/exercises/13_error_handling/errors6.rs index aaf0948e..8b63ff1f 100644 --- a/exercises/13_error_handling/errors6.rs +++ b/exercises/13_error_handling/errors6.rs @@ -10,6 +10,7 @@ // hint. // I AM NOT DONE +// NOTE: 重要 use std::num::ParseIntError; @@ -25,13 +26,26 @@ impl ParsePosNonzeroError { ParsePosNonzeroError::Creation(err) } // TODO: add another error conversion function here. - // fn from_parseint... + fn from_parseint(s: &str) -> Result { + match s.parse::() { + Ok(result) => { + if result == 0 { + Err(ParsePosNonzeroError::Creation(CreationError::Zero)) + } else if result < 0 { + Err(ParsePosNonzeroError::Creation(CreationError::Negative)) + } else { + Ok(result) + } + }, + Err(err) => Err(ParsePosNonzeroError::ParseInt(err)) + } + } } fn parse_pos_nonzero(s: &str) -> Result { // TODO: change this to return an appropriate error instead of panicking // when `parse()` returns an error. - let x: i64 = s.parse().unwrap(); + let x: i64 = ParsePosNonzeroError::from_parseint(s)?; PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation) }