3 ms·
Using an Option instead of a pointer buys you the inability to forget to check for nil. Just need to make sure the Option exposes the internal value only throu
by Mawr 2y ago
Using an Option instead of a pointer buys you the inability to forget to check for nil.
Just need to make sure the Option exposes the internal value only through:
func (o Option[Value]) Get() (Value, bool) {
return o.value, o.exists
}
Accessing the value is then forced to look like this:
if value, ok := option.Get(); ok {
// value is valid
}
// value is invalid
Thus, there's no possibility of an accidental nil pointer dereference, which I think is a big win.
A Result type would bring a similar benefit of fixing the few edge cases where an error may accidentally not be handled. Although I don't think it'd be worth the cost of switching over.
- Hendrikto 2y agoHow is that better than if value != nil { // value is valid } // value is invalid ? Of course, this is often left out, but you can just as easily do: value, _ := option.Get() So this is just not true: > Using an Option instead of a pointer buys you the inability to forget to check for nil.
- Mawr 2y agoIt's better because you do not need to remember to check for nil, the compiler will remind you every time by erroring out until you handle the second return value of `option.Get()`. > Of course, this is often left out, but you can just as easily do: Unfortunately it gets brought up pretty much every time in these discussions. Deliberate attempts to circumvent safety are not part of the threat model. The goal is prevention of accidental mistakes. Nothing can ultimately stop you from disabling all safeties, pointing the shotgun at your foot and pulling the trigger.