Hacker News new | ask | show | jobs
by librexpr 1406 days ago
Maybe it would have been a good idea to have two names for unwrap, one which would mean "I'm certain that this value will always be okay", and another which would mean "I'm taking a shortcut because I'm writing a script or just want it to compile for now". Maybe a longer name like "assert_valid()" for the one where you're sure it's okay. That might make it easier to find the places where shortcuts were taken and forgotten.
3 comments

Consider using anyhow. At that point, unwrap isn't a shortcut anymore except for one place: you are in a deeply nested function call and you suddenly realize you need to bubble up an error a few layers. Now you have to change a bunch of function signatures.

I don't find myself in that position too frequently. Certainly not enough to warrant two identical but differently named functions.

In that case, I would suggest coming up with your own pattern. Perhaps an unwrap() with a FIXME comment. Or a expect("FIXME").

> In that case, I would suggest coming up with your own pattern. Perhaps an unwrap() with a FIXME comment. Or a expect("FIXME").

That's the sort of thing that's a lot more effective if everyone does the same thing. So it's worth trying to standardise across the community.

That's a non-sequitur. Just because it would be more effective doesn't mean it's actually worth trying to standardize. I see no accounting of trade offs. I see no accounting for how common the pattern is in practice. I see no accounting for the confusion that will result when there are two methods that behave identically, are named different and should be used in two very subtly different and nuanced ways.

I'd prefer if you just leave me alone to be honest.

There is! `expect()`
I think this is a good answer. People should use `expect` for this "I'm sure this is fine" case, with descriptive text about why it's fine.
Or you can invert it and use `.expect("TODO add error handling")`
Maybe if Rust code wasn't so hard to get working at all, then more of it would work correctly (including checking errors instead of giving up and unwrapping).
not sure what you're referring to, but yes having a first iteration of code with unwrap here and there, and then a second one with proper error handling is a viable strategy. the "loudness" of unwrap makes it super easy to notice any leftover in code review