3 ms·
> but I love Option/Result types more than Go's error approach The thing is, these don't add much on their own. You'd have to bring in pattern matching and/or
by Kamq 2y ago
> but I love Option/Result types more than Go's error approach
The thing is, these don't add much on their own. You'd have to bring in pattern matching and/or a bunch of other things* that would significantly complicate the language.
For example, with what's currently in the language, you could definitely have an option type. You'd just be limited to roughly an api that's `func (o Option[T]) IsEmpty() bool` and `func (o Option[T]) Get() T`. And these would just check if the underlying point is nil and dereference it. You can already do that with pointers. Errors/Result are similar.
A `try` keyword that expands `x := try thingThatProducesErr()` to:
x, err := thingThatProducesErr()
if err != nil {
return {zero values of the rest of the function signature}, err
}
Might be more useful in go (you could have a similar one for pointers).
* at the very least generic methods for flat map shenanigans
- Mawr 2y agoUsing 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.