3 ms·
I tend to agree with preferring alternatives (?, Expect, unwrap_or_else) to unwrap in most cases, but I do still find myself using unwrap in cases where it's ba
by Macha 4y ago
I tend to agree with preferring alternatives (?, Expect, unwrap_or_else) to unwrap in most cases, but I do still find myself using unwrap in cases where it's basically impossible for it to fail. e.g. imagine a parse method that returns a Result in case the input is not a valid whatever, but I've just called it with a literal value.
At the same time, looking at one of my codebase, 90% of such cases are in my test code
- mcronce 4y agoI agree with you. My general rule of thumb is that I use `unwrap()` for cases where the panic should be unreachable, and is at least reasonably easy to prove it's unreachable. Otherwise, `?` in 90% of code, with panics far up the stack, e.g. in `main()`
- masklinn 4y ago> My general rule of thumb is that I use `unwrap()` for cases where the panic should be unreachable, and is at least reasonably easy to prove it's unreachable. I don’t agree with that. To me unwrap straddles the line between “I don’t care to think about this right now” and “I don’t care about that case”. If I can prove it does not happen then it get an “expect” with a justification. Or even a map_err(|_| unreachable!(reasoning)) if I’m feeling really fancy. unwrap acts as a todo, I can grep for it and if I see one I know it’s something to fix.