Rustlings recoverable errors

I am having a bit of trouble with errors2.rs in rustlings. It's a bit annoying because it feels like I've had a bit of a mental block on how to do this correctly.

from the book rustlings often refers to:
https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html

I tried unwrap and expect however they didn't seem to match what the rustlings test wanted. Can someone share a little wisdom on where I've gone wrong with this?

Since you tried unwrap and expect I'm guessing you understand that here:

    let qty = item_quantity.parse::<i32>();

qty is a Result and you need to get the i32 out from inside of it. However, the other key part of the exercise is

and in [the case of an error], we want to immediately return that error from our function

unwrap and expect panic instead of returning, i.e. propagating, the error. (Panicking is not considered a form of returning in Rust, like one might argue exceptions are in other languages, as the panic may directly cause an abort (among other reasons).) They want you to figure out how to return the error.

[spoilers ahead]

Following that chapter, you could match on the returned value:

    let qty = match item_quantity.parse::<i32>() {
        Ok(q) => q,
        Err(e) => return Err(e),
    };

Or, you could use the ? operator:

    let qty = item_quantity.parse::<i32>()?;
    //                                    ^
1 Like

Hi there @jcarty ,

@quinedot 's method is the correct explanation but I just wanted to join in the conversation

In order to have recoverable error's that do not panic, Rust has an enum called
Result<R, E>

This enum has two branches: Ok() and Err()

So use this syntax

let qty = match item_quantity.parse::<i32>(){
    Ok(r)=>r,
    Err(e)=> Err(e)
};

Or the shorter syntax is adding a ? after ()

Hope this helped,

println!("Happy Coding !");

It helped a lot. I feel a little bit silly now but for some reason reading the problem it self didn't click at first.

Thank you @quinedot and @Liftoff-Studios .

1 Like

No Problem :+1:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.