News for hackers. Stuff that matters.
Re:Rust should not have provided `unwrap` by Animats on Friday July 15, 2022 @02:06PM (#32111085)
I tend to agree.

You can use "unwrap()" on an Option, but you can't use "?". You have to write something like

    let val = v.ok_or(anyhow!("Error message goes here"))?;
which is a bit unwieldy.

    fn square(v: &Option<f32>) -> f32 {
        Ok(v.unwrap()*v.unwrap())
    }
becomes

    fn square(v: &Option<f32>) -> Result<f32, Error> {
        let val = v.ok_or(anyhow!("None value sent to square"))?;
        Ok(val*val)
    }
A default message would be useful.

Bailing out of the middle of a map expression's closure is complicated. In that situation, "?" causes a return of the expression in the closure, not the whole map. There's a clever way around this.[1] It supposedly gets optimized so that the iteration quits early, and an array of Result types is not generated and then flattened.

You never really need unwrap, but the "right way" can be verbose.

[1] https://stackoverflow.com/questions/26368288/how-do-i-stop-i...

Re:Rust should not have provided `unwrap` by throwaway234232 on Friday July 15, 2022 @02:54PM (#32111571)
Your example doesn't help your argument here, as square should be taking `T` instead of `Option<T>`, a good use case for `Option::map`.

But if you are speaking about ergonomics of handling Options, it is being improved upon with the usage of try operators with Options as well as possibly seeing try expressions in the near future.

I don't think lack of ergonomics is a good justification for usage of unwrap, but that is entirely subjective. However, I do see the misappropriation of `unwrap` as a signal that the ergonomics in Rust are lacking and it's something that needs to be addressed, so again I do sympathize.

Re:Rust should not have provided `unwrap` by stormbrew on Friday July 15, 2022 @02:26PM (#32111300)
For the specific examples you have here you can shorten it a bit and use anyhow's OptionExt::context and avoid the closure. Someday maybe we'll have postfix macros and you'll even be able to format in it.
Re:Rust should not have provided `unwrap` by brink on Friday July 15, 2022 @02:09PM (#32111114)
You can use a "?" on an option if the return type of the function is also option.