Generic functions to get optional values
By convention, optional values in Go are pointers:
type Input struct {
RequiredField string
OptionalField *string
}
But such structs cannot be initialized in a single expression:
in := Input{
RequiredField: "works",
OptionalField: &("does not work"),
}
And accessing optional fields makes code look ugly:
if in.OptionalField != nil && *in.OptionalField == "value" {
...
}
Sometimes even unsafe:
value := "v1"
in.OptionalField = &value
value = "v2" // ups... in.OptionalField is changed too!
One-line initialization:
import "github.com/elgopher/ptr"
in := Input{
RequiredField: "works",
OptionalField: ptr.To("this also works"),
}
Getting values without boilerplate code:
if ptr.Value(in.OptionalField) == "value" {
// if in.OptionalField is nil then zero value is returned ("" for string)
...
}
or get value by specifying the default value when in.OptionalField is nil:
v := ptr.ValueOrDefault(in.OptionalField, "defaultValue")
Safe code:
value := "v1"
in.OptionalField = ptr.To(value)
value = "v2" // in.OptionalField is not changed
or
newPointer := ptr.Copy(in.OptionalField)
go get github.com/elgopher/ptr@latest