by Mawr · 4y ago · 0 comments
type Optional[T any] struct {
value *T
}
Don't use a pointer - it's bad for performance. func MakeOptional[T any](value *T) Optional[T] {
Use `New` instead - it's the idiomatic name for a constructor in Go. Drop the `Optional` part - the module name suffices - the caller will see: `opt.New`. Personally I just call the module `optional`, I think it's clearer: `optional.New`. func (o* Optional[T]) Unwrap() (T, error) {
1. `Unwrap` reminds me of Rust's .Unwrap, which panics. Seems confusing.2. There's no error here, the situation is equivalent to a missing key in a map - it's enough to return a bool.
Here's my implementation so far: https://gist.github.com/Mawr-BF2/0a60da26f66b82ee87b98b03336.... Only thing I'm not sure about is whether the JSON serialization methods are necessary.
I agree with peer comment that we should likely defer to the original type for JSON serialization.
Where do you get this from? I've tried unsuccessfully to find such naming/design guidelines.
[1]: https://github.com/golang/go/commit/85e7bee19f9f26dfca414b1e...
Pointers to pointers are generally something you try to avoid if possible.
But any benefits of the packing are gone whether I make a pointer or not.
And either way, no nested pointers are involved. We’re not taking pointers to options in either case.
to use a tired example: when getting a value out of a map via some `myMap.get(key)`, you may want to distinguish "not present" = `None` and "present, with value null" = `Some(null)`
the right solution is to just not have nulls in the first place, then there's no problem ;)
Some(null) is not a valid result.
The whole point of the Option type is to let you know:
a) we got a result: Some(value)
b) there is no result: None
That means you must have Optional[*sync.Mutex]. Then what's the point?