Guidelines:
Tip
The super quick summary is: use omitzero
Unless you need to identify an empty map/slice/interface, then use omitempty
.
If you need to identify if value was deliberately set to the zero type, use a pointer.
If you have specific zero requirements define custom type with IsZero
method.
- to filter out a nil map, use
omitzero
- to filter out a nil map and an empty map, use
omitempty
- to filter out a nil slice, use
omitzero
- to filter out a nil slice and an empty slice, use
omitempty
- to filter out an empty struct, use
omitzero
** - to filter out a zero time, use
omitzero
- to filter out a bool, use
omitzero
** Go checks if all the struct's fields are their respective zero values or if it has a custom
IsZero()
bool method that returns true.
Here is a contrived example of a custom int type that implements IsZero
to trick 0 to be shown (but really, the implementation can be whatever makes sense for your application):
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Field CustomInt `json:"field,omitzero"`
}
type CustomInt int
func (i CustomInt) IsZero() bool {
return i == -1
}
func main() {
d1 := Data{}
j1, _ := json.Marshal(d1)
fmt.Println(string(j1)) // {"field":0}
d2 := Data{Field: 0}
j2, _ := json.Marshal(d2)
fmt.Println(string(j2)) // {"field":0}
d3 := Data{Field: 1}
j3, _ := json.Marshal(d3)
fmt.Println(string(j3)) // {"field":1}
}