3 ms·
TLDR; - While I agree unwrap/expect should not typically be used often in production code there are enough exception cases that Rust would be MUCH worse if they
by nu11ptr 4y ago
TLDR; - While I agree unwrap/expect should not typically be used often in production code there are enough exception cases that Rust would be MUCH worse if they didn't exist
Longer version:
Only skimmed, but I disagree, although I thought the same thing when I started. It sounds wonderful to have panic-free Rust but when when you sit down and think about how that would work you quickly realize it is a trade off between boilerplate and convenience.
Rust code can be broken down into mostly three "types":
1. Safe, and can't panic (calls nothing that can panic)
2. Safe, can panic (.unwrap, .expect, indexing, etc.)
3. Unsafe, could do anything
The goal when writing Rust IMO is to try and get as much as possible in #1, control #2 carefully by closely held invariants, and avoid #3 as much as possible (in many programs, this turns into no unsafe at all).
The problem with avoiding #2 entirely is you will quickly get code that is hard to write, harder to understand, etc. Most often you will see situations like "I just proved this is x in length, so I can always index this with this value". If you don't do this you will have lots of error checking that effectively does nothing. I admit this happens rarely for Option/Result and in prod code I rarely use unwrap/expect, however, some code would be very tedious to write without unwrap or potentially panicking code, so unwrap/expect can be valuable for things like tests, examples, and rapid prototyping.
I should probably add that I actually agree with the author that in the _typical_ case, you should not be using unwrap/expect, but either pattern matching it or propigating it with ?, but the exceptions to this (testing/examples/prototyping/corner cases) are important enough that I'm very glad Rust has the "escape hatch" of unwrap/expect.