rCore-Tutorial icon indicating copy to clipboard operation
rCore-Tutorial copied to clipboard

Rustlings error6.rs

Open iHichew opened this issue 4 years ago • 4 comments

寻求一下rustlings error_handling 部分的error6.rs的解答思路 (Rustings好像这一部分有变化,有的版本可能没有error6) 题目链接:
https://github.com/rust-lang/rustlings/blob/main/exercises/error_handling/errors6.rs

iHichew avatar Jul 10 '21 14:07 iHichew

我在这个页面做了解答并测试通过:https://codechina.csdn.net/u011732390/morningglory/-/tree/master/step0/errors/error6 star please

MorningGloryy avatar Jul 16 '21 07:07 MorningGloryy

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)), }

}

MorningGloryy avatar Jul 23 '21 09:07 MorningGloryy

There are two ways to handle.

  1. legacy way, using a nested match expression
  2. 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)
}

sawaYch avatar Jan 05 '22 20:01 sawaYch

with nested match exp:

match s.parse() {
    Ok(x) => PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::Creation),
    Err(err) => Err(ParsePosNonzeroError::ParseInt(err)),
}

hscspring avatar Jun 30 '22 16:06 hscspring