Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling, map_err and error type conversion

I'm learning rust and I'm currently working on the exercise here.

So far I've come up with the following:

impl ParsePosNonzeroError {
   ...
   ...
   fn from_parseint(err: ParseIntError) -> ParsePosNonzeroError {
       ParsePosNonzeroError::ParseInt(err)
   }
fn parse_pos_nonzero(s: &str)
-> Result<PositiveNonzeroInteger, ParsePosNonzeroError>
{
     let x: i64 = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parseint);
     PositiveNonzeroInteger::new(x).map_err(ParsePosNonzeroError::from_creation)
}

When I do this I get the error message:

! Compiling of exercises/error_handling/errors6.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
  --> exercises/error_handling/errors6.rs:34:18
   |
34 |       let x: i64 = s.parse::<i64>()
   |  ____________---___^
   | |            |
   | |            expected due to this
35 | |         .map_err(ParsePosNonzeroError::from_parseint);
   | |_____________________________________________________^ expected `i64`, found enum `Result`
   |
   = note: expected type `i64`
              found enum `Result<i64, ParsePosNonzeroError>`

Going through the documentation of map_err I see the following: Maps a Result<T, E> to Result<T, F> by applying a function to a contained Err value, leaving an Ok value untouched.

What am I missing? Why is this not working?

like image 660
learnlearnlearn Avatar asked Oct 16 '25 11:10

learnlearnlearn


1 Answers

map_err is returning a Result<i64, ParsePosNonzeroError> but you're trying to affect it to x, which you declared as an i64 variable. You need to add a ? so that an Err result will be returned and an Ok result will be unwrapped: let x = s.parse::<i64>().map_err(ParsePosNonzeroError::from_parseint)?;

like image 57
Jmb Avatar answered Oct 18 '25 07:10

Jmb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!