#help with rustlings exercise errors6

3 messages · Page 1 of 1 (latest)

copper aspen
#

The problem in that function is that s.parse() returns a Result, and that Result is immediately .unwrap(). When you unwrap a Result (or similar, like Option), you get the Ok() value if that's what the Result is. But if Result is Err, then unwrap() will throw a panic.
(https://doc.rust-lang.org/std/result/enum.Result.html#method.unwrap)

The exercise wants you to change this line such that if .parse() fails, that you return an error instead of panicing.

#

Hopefully that offers some help? Is there something specific you're unsure how to do, or something that doesn't make sense?

austere kettle
#

The error that the function wants to return is this enum here:

enum ParsePosNonzeroError {
    Creation(CreationError),
    ParseInt(ParseIntError),
}

So the variants indicate that it can be constructed from a value of type CreationError or ParseIntError

The already existing function here is able to convert from a CreationError to a ParsePosNonzeroError

fn from_creation(err: CreationError) -> ParsePosNonzeroError {
    ParsePosNonzeroError::Creation(err)
}

And it's asking you to write a similar function from_parseint which takes a ParseIntError and converts it to a ParsePosNonzeroError - that's the first part

Then notice that in the parse_pos_nonzero function, there is already this pattern for "do something which returns a Result, and apply a function to change the error type"

PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)

You'll want to do something similar here to change the error type of the Result from parse using ParsePosNonzeroError::from_parseint

It will be useful to take a look at this page too for an idiomatic approach: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html#a-shortcut-for-propagating-errors-the--operator