3 ms·
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 {
by Mawr 3y ago
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/0a60da26f66b82ee87b98b03336e1f84 https://gist.github.com/MawrBF2/0a60da26f66b82ee87b98b03336e...