Library for conveniently and safely dealing with optional (nullable) values.
Note: Requires Go 1.18 with generics support.
$ go get github.com/adolfo/optional-go
package main
import (
"github.com/adolfo/optional-go"
)
// Optional string
optStr := optional.Of("foo")
// Optional int
optInt := optional.Of(5)
// Optional float64
optFlt := optional.Of(9.99)
// Optional struct
type Thing struct {
foo int
bar string
}
optThing := optional.Of(Thing{42, "baz"})
// Optional string with nil value
nilStr := optional.OfNil[string]()
// Optional int with nil value
nilInt := optional.OfNil[int]()
// Nil struct
nilThg := optional.OfNil[Thing]()
// Optional int with nil value
var nilInt optional.Value[int]
// Optional string with nil value
nilStr := optional.Value[string]{}
o := optional.OfNil[int]
// Set new value
o.Set(42)
// Clearing value and resetting to nil
o.SetNil()
// Set invalid value
o.Set("fred") // compiler error; type is Optional.Value[int]
o := optional.Of(42)
// Safely get underlying optional value
if ok, val := o.Get(); ok {
fmt.Println(val) // prints 42
}
// Unsafely get value
fmt.Println(o.MustGet()) // prints 42
o.SetNil()
fmt.Println(o.MustGet()) // panics
o := optional.Of("foo")
fmt.Println(o.GetOr("fred")) // prints "foo"
o.SetNil()
fmt.Println(o.GetOr("fred")) // prints "fred"
if o.HasValue() {
fmt.Println("has value")
}
if o.IsNil() {
fmt.Println("value is nil")
}
type Person struct {
Name optional.Value[string] `json:"name"`
Age optional.Value[int] `json:"age"`
}
j := `{ "name": null, "age": 42 }`
p := new(Person)
json.Unmarshal([]byte(j), p)
fmt.Println("name is %s", p.Name.GetOr("Unknown"))
// prints "name is Unknown" since `name` was null
Released under the MIT License