Hacker News new | past | comments | ask | show | jobs | submit login

You can make such a type and it works well in practice.

First we define the type, hiding the pointer/non-existent value:

    type Optional[Value any] struct {
        value  Value
        exists bool
    }
Then we expose it through a method:

    func (o Optional[Value]) Get() (Value, bool) {
        return o.value, o.exists
    }
Accessing the value then has to look like this:

    if value, ok := optional.Get(); ok {
        // value is valid
    }
    // value is invalid
This forces us to handle the nil/optional code path.

Here's a full implementation I wrote a while back: https://gist.github.com/MawrBF2/0a60da26f66b82ee87b98b03336e...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: