The optional
type for golang, implemented with generics (go 1.18).
var v optional.Type[int] = optional.New(123)
if unwrapped, ok := v.Value(); ok {
unwrapped // 123
}
v.IsNil() // false
v.ForceValue() // 123
optional.New(XX)
If XX is nil, it returns Nil
optional.Nil()
- (
optional.FromPtr(XXX)
returns optional.Nil() if pointer is nil)
Value()
var v = optional.New(123)
if unwrapped, ok := v.Value(); ok {
unwrapped // 123
}
-
ForceValue()
-
IsNil()
-
ValueOrDefault(XX)
-
ValueOrLazyDefault(f)
- Map
optional.Map( optional.New(123), func(t int) string {
return fmt.Sprintf("hello %d", t)
}) // optional.Type[string]
- Compact
var v = optional.New(optional.New(123))
optional.Compact(v) // optional.Type[int]
json Marshal and Umarshal supported.
If Nil, the encoded json data is null
.
MIT