67
u/SelfDistinction Oct 23 '26
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
20
18
u/switch161 Oct 23 '26
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.
10
u/scottmcmrust Oct 23 '26
Notably, one reason
Option::unwrapis often fine is that you never want to report "an option was none" to a user anyway.6
u/Kinrany Oct 23 '26
/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 Oct 23 '26
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
23
u/Major_Barnulf ๐๐ (๐) Oct 23 '26
unwrap() fails right away, with no further process corruption, with a legible trace. This is miles ahead of C/C++ experience.
6
4
u/BosonCollider Oct 23 '26
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
3
2
2
2
2
u/Background_Class_558 Oct 24 '26
.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 Oct 24 '26
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.
3
u/a_aniq Oct 23 '26
If result: For toy apps using unwrap is okay. Otherwise you handle them properly.
For options, you handle None scenario as part of application logic.
Unwrap is like global variable. You don't use it in production app unless you are absolutely sure.
1
1
u/No_Frame3855 Oct 24 '26
To be fair sometimes you need unwrap and unsafe, in tests, embedded sometimes, etc
1
1
1
113
u/FabianButHere Oct 23 '26
Only. Unwrap. When. An. Error. Is. Impossible.