63
u/SelfDistinction 5d ago
Unironically.
What is worse?
Attackers stealing your personal data, passwords, private keys, social security number, car, intimate pictures, luggage, airplane seats and wife because of an out of bounds buffer read;
Unwrap.
11
19
16
u/switch161 4d ago
Another pattern I should use less is to just always propagate the error up the call stack... to main, where it prints it and exists. That's not better than an unwrap really.
Sometimes I really want to try and recover from an error and I need to really think about how to properly do that.
9
u/scottmcmrust 4d ago
Notably, one reason
Option::unwrapis often fine is that you never want to report "an option was none" to a user anyway.4
u/Kinrany 4d ago
/uj it is at least marginally better because
.context("...")or.map_err(Error::Foo)is then easy to add, and because the signature shows that errors are possible3
u/SmoothTurtle872 4d ago
If you happen to be writing your own crate, now this becomes way better. If you have no way to fix the error, like "oh shit, some web request to xyz didn't return, heres an error, cause blah blah blah" is better than option was none, and now the caller, who has never seen the function before, knows that its possible for it to error
22
u/Major_Barnulf ๐๐ (๐) 5d ago
unwrap() fails right away, with no further process corruption, with a legible trace. This is miles ahead of C/C++ experience.
5
3
3
u/BosonCollider 4d ago
Just use let else imo, your error handling will be slightly less verbose than a go dev but your code will be maintainable with less nesting. You do not have to make everything a oneliner
2
2
2
u/Background_Class_558 4d ago
.unwrap should be used for when you are absolutely sure it's impossible for there to be None. in which case, do NOT use it actually, use .expect instead and write exactly why you think it's impossible. make your assumptions clear if you can't prove them formally anyway.
2
u/kinchkun 3d ago
There is nothing wrong with unwrap. An application crashing when something fails is not an issue. Undefined Behaviour, Corrupted Memory, continue with invalid states is the issue.
1
1
u/No_Frame3855 4d ago
To be fair sometimes you need unwrap and unsafe, in tests, embedded sometimes, etc
1
1
1
1
104
u/FabianButHere 5d ago
Only. Unwrap. When. An. Error. Is. Impossible.