rCore-Tutorial
rCore-Tutorial copied to clipboard
Rustlings error6.rs
寻求一下rustlings error_handling 部分的error6.rs的解答思路
(Rustings好像这一部分有变化,有的版本可能没有error6)
题目链接:
https://github.com/rust-lang/rustlings/blob/main/exercises/error_handling/errors6.rs
我在这个页面做了解答并测试通过:https://codechina.csdn.net/u011732390/morningglory/-/tree/master/step0/errors/error6 star please
impl ParsePosNonzeroError { fn from_creation(err: CreationError) -> ParsePosNonzeroError { ParsePosNonzeroError::Creation(err) } // TODO: add another error conversion function here. fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError { ParsePosNonzeroError::ParseInt(err) } }
fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
// TODO: change this to return an appropriate error instead of panicking
// when parse() returns an error.
match s.parse() {
Ok(x) => {match PositiveNonzeroInteger::new(x) {
Ok(PositiveNonzeroInteger(x)) => Ok(PositiveNonzeroInteger(x)),
Err(CreationError::Negative) => Err(ParsePosNonzeroError::from_creation(CreationError::Negative)),
Err(CreationError::Zero) => Err(ParsePosNonzeroError::from_creation(CreationError::Zero)),
}
}
Err(ParseIntError) => Err(ParsePosNonzeroError::from_parseint(ParseIntError)),
}
}
There are two ways to handle.
- legacy way, using a nested match expression
- use
.map_err()
for the second way:
fn parse_pos_nonzero(s: &str) -> Result<PositiveNonzeroInteger, ParsePosNonzeroError> {
let x: i64 = s.parse().map_err(ParsePosNonzeroError::from_parseInt)?;
PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}
with nested match exp:
match s.parse() {
Ok(x) => PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::Creation),
Err(err) => Err(ParsePosNonzeroError::ParseInt(err)),
}