3 ms·
Yeah, but using Option is encouraged, while using Option.unwrap as error handling is discouraged. Ok, to be more precise, Option in Rust, isn't a null pointer.
by Ygg2 9y ago
Yeah, but using Option is encouraged, while using Option.unwrap as error handling is discouraged.
Ok, to be more precise, Option in Rust, isn't a null pointer. It's a nullable pointer. Practically speaking only Option::None is the null pointer. You can either deal with it (using if-let or match) or you can `unwrap` and assume it's never null. If you make that assumption and if and only if it was actually Option::None, will it throw null pointer exception.
In contrast something like C/Java will allow you to use your nullable pointer (because all pointers/references are nullable by default) without any check and it's relatively easy to skip this step. In Rust, it's relatively hard to skip this step.
EDIT: Changed per burntsushi post.
- burntsushi 9y agoUse of Option.unwrap (or Option.expect) in libraries is not discouraged, and it shouldn't be. It's an excellent way of checking a runtime invariant. Use of Option.unwrap is discouraged for error handling. Stated differently, if a library you're using causes a panic, then it should be interpreted as a bug. The bug might be in the library, or it might be in the way that the library is being used (assuming the panic conditions have been documented as part of the library API's contract). A separate argument says that you should reduce the number of places where your code can panic. That sounds like a fine goal to strive for, but must be balanced with other things.