In golang v1, unfortunately, there is no nice builtin way to represent optional
struct
fields for primitives whose zero value is individualized for each
primitive. A lot of debating has been done and people hold different opinions
as to what is the best solution. This library is my personal preferred way
of dealing with the situation.
package main
import (
"fmt"
"github.com/trivigy/ref"
)
type Sample struct {
Field *string `json:"field,omitempty"`
}
func main() {
result := Sample{
Field: ref.String("example"),
}
if result.Field != nil {
fmt.Print("'Field' is set")
}
}
If you hold another opinion feel free to share it either via discord or on golang github channels. Or better yet share a PR with a new link added above.