Sometimes being nice really pays off.
Sometimes being nice really pays off.
std::optional<> is an extremely useful and welcome addition to C++ that improves code quality, is easy to understand, and has easy to reason about code generation.
No doubt there is something that could be demonstrated in Rust with Option that is compelling, but I'd rather people showed that so a basis for comparison with modern C++ code can be made.
I suspect in practice these arguments make little difference to real world code.
Here's the big issue: unchecked access to std::optional with operator* has undefined behavior when there's no value.
This is unforgivably bad design since you can enforce exhaustive checking at compile time, but C++ isn't going in that direction.
std::optional offers value() for checked access too, but that checks at runtime and throws an exception.
It is possible to have an optional with no runtime check, no undefined behaviour, and guaranteed handling of both cases by checking at compile time. This is what Rust offers.
Undefined behaviour being easy to invoke absolutely does matter for real world code.
An equivalent API with no UB is just strictly better.
"Make everything constexpr" isn't a real solution to UB, in the same way that "make all functions pure" isn't a solution for managing side effects.
Not adding UB to your APIs, on the other hand, is a real solution.
unsafe fn super_unwrap<T>(x: Option<T>) -> T {
match x {
Some(val) => val,
None => unreachable_unchecked!(),
}
}
But defaults matter, and Rust certainly doesn’t make this kind of thing ergonomic (which is a correct decision on the Rust designers’ part).Including UB in easy to misuse places is totally unnecessary and a footgun which really does cause issues in real code.
Because all Rust's methods can be called as free functions, you can literally write Option::unwrap_unchecked for the same behaviour, or you can some_option.unwrap_unchecked() (in both cases you will need to be in unsafe context for this to be allowed and should write a SAFETY comment explaining why you're sure it's correct)