Optional is a tool that generates option type wrappers around a given type T.
It is also a library that provides option types for the primitive Go types.
In Go, variables declared without an explicit initial value are given their zero value. Most of the time this is what you want, but sometimes you want to be able to tell if a variable was set or if it's just a zero value. That's where option types come in handy.
Note: v0.6.0 introduces a potential breaking change to anyone depending on marshalling non-present values to their zero values instead of null. See: #9 for more context.
Option types also marshal to/from JSON as you would expect:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var value = struct {
Field optional.String `json:"field,omitempty"`
}{
Field: optional.NewString("bar"),
}
out, _ := json.Marshal(value)
fmt.Println(string(out))
// outputs: {"field":"bar"}
}package main
import (
"encoding/json"
"fmt"
)
func main() {
var value = &struct {
Field optional.String `json:"field,omitempty"`
}{}
_ = json.Unmarshal([]byte(`{"field":"bar"}`), value)
value.Field.If(func(s string) {
fmt.Println(s)
})
// outputs: bar
}See example_test.go for more examples.
go get -u github.com/markphelps/optional/cmd/optional
Typically this process would be run using go generate, like this:
//go:generate optional -type=Foorunning this command:
optional -type=Fooin the same directory will create the file optional_foo.go containing a definition of:
type OptionalFoo struct {
...
}The default type is OptionalT or optionalT (depending on if the type is exported) and output file is optional_t.go. This can be overridden with the -output flag.
- bool
- byte
- complex128
- complex64
- float32
- float64
- int
- int16
- int32
- int64
- int8
- rune
- string
- uint
- uint16
- uint32
- uint64
- uint8
- uintptr
- error
package main
import (
"fmt"
"github.com/markphelps/optional"
)
func main() {
s := optional.NewString("foo")
value, err := s.Get()
if err != nil {
// handle error!
} else {
fmt.Println(value)
}
t := optional.String{}
fmt.Println(t.OrElse("bar"))
}See example_test.go and the documentation for more usage.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
If changing the API you may need to update the golden files for your tests to pass by running go test ./cmd/optional/... -update.