Reference: https://willnorris.com/2014/05/go-rest-apis-and-pointers/
If a struct field isn't populated, and is marshalled to JSON, then the field's zero value will be used (e.g. type string zero value == "", type int zero value == 0).
You can use omitempty
to prevent the field from being marshalled, but then you won't know if the zero value was intentional or not (e.g. a user might want to set an type int field to zero or a type string field to an empty string).
To avoid that situation you need to have the field be set to a pointer of the type. This is because the zero value for a pointer is nil
. This means if the field is nil
then the field was never set but if it looks like a zero value for the type being pointed to, then you know it was set to the zero value intentionally.