Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rustlings error6.rs #146

Open
iHichew opened this issue Jul 10, 2021 · 4 comments
Open

Rustlings error6.rs #146

iHichew opened this issue Jul 10, 2021 · 4 comments
Labels
learning Learner discussions

Comments

@iHichew
Copy link

iHichew commented Jul 10, 2021

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

@iHichew iHichew added the learning Learner discussions label Jul 10, 2021
@MorningGloryy
Copy link

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

@MorningGloryy
Copy link

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

}

@sawaYch
Copy link

sawaYch commented Jan 5, 2022

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

@hscspring
Copy link

hscspring commented Jun 30, 2022

with nested match exp:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
learning Learner discussions
Projects
None yet
Development

No branches or pull requests

4 participants