Re:Trying Out Generics in Go
by hmmdar on Thursday December 16, 2021 @01:37PM
(#29581968)
Another way to do `Option` without pointers could be similar to the following with a struct with two members.
With this pattern you're able to use `Option` as a value without pointers.
Alternative separate `Get` and `IsSet` methods, is to combine them into one, similar to map look up pattern.
[ Parent
| on HN ]
I agree with `Get` returning `(T, bool)` I don't see why one would want to return an `error`.
I don't understand your example, `isSet` is always true and can never be false. Missed something?
It works because it's false when uninitialized (as default value). So if not initialized it represents Nothing value. When it is initialized it's Just T.
The only time `IsSet` would be false is when `NewOption` was not used to initialize the value.
e.g.
var o Option[int32]
or could have `None` helper func None[T any]() Option[T] { return Option[T]{} }
o := None[int32]()