Hacker News new | ask | show | jobs
by doctor_eval 1358 days ago
> No default struct values

I love Go too but this does drive me nuts, especially when parsing JSON and wanting to set sane defaults for missing values. Like, for example, booleans that should default to "true".

2 comments

For that use case, I think that you can assign your defaults before passing your target struct to the unmarshaller.

The unmarshaller will iterate on the json input and set struct fields when json fields are found. This means that struct fields that don't match the json are ignored, and values you have set before will be left as is.

While true, this approach doesn’t work for nested structs, which are instantiated by the parser.
Write a DefaultFoo function which returns a Foo with default values set. Then unmarshal into that.