4 ms·
I still got a few unwrap panics in libraries I've used (not in example code). Also: Using a null pointer in C++ is also heavily discouraged ;)
by jhasse 9y ago
I still got a few unwrap panics in libraries I've used (not in example code).
Also: Using a null pointer in C++ is also heavily discouraged ;)
- int_19h 9y agoOnly if you are talking about raw pointers. Using unique_ptr or shared_ptr to hold nullptr is still pretty common in C++.
- Ygg2 9y agoYeah, 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.
- topspin 9y agoRight, but what you did not get was undefined behavior. That is the real difference, not that Rust "discourages" unwrap(). unwrap() panics, while unfortunate, are well defined.
- jhasse 9y agoIn reality, this doesn't make a difference though ;)
- topspin 9y agoHalting in a defined manner vs. continuing computation while undefined conditions prevail are fundamentally different outcomes. This is indeed a difference.
- jhasse 9y agoComputation doesn't continue, it segfaults.
- topspin 9y agoYou simply cannot know that and your assertion reveals a lack of understanding. Computation may continue indefinitely, unintentionally distributing your private keys or doing some other heinous thing forever, without any sort of MMU trap. Undefined means undefined, not 'segfault.'
- jhasse 9y agoI said "in reality". Can you give me an (realistic) example where using a nullptr doesn't result in a segfault?