nullable base types in go
recently I've been writing a lot of Go code using Amazon's DynamoDB service, which utilizes JSON to format requests and responses. naturally, I have been writing packages which contain types which map these JSON formats closely. in many cases, Amazon allows certain fields to be optional. below I illustrate a hypothetical JSON format with optional fields, showing what would be permitted:
an initial naive attempt to create a Go struct might result in something like this:
but when passed through Go's MarshalJSON method, such a naive struct will produce JSON serializations of the default values for these types - 0 for the uint64, and "" for the string, even if the user has not set them in their own Foo instance.
It would be nice if these fields, if unset by the user from their defaults, would be serialized as null. here is one method for achieving this: create alias types for the base type in question and override the default MarshalJSON method on the aliased type only. like:
and rewrite our original type like
now our serialization will produce null for uninitialized optional fields.
last update 2013-06-05