3 ms·
> 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, f
by doctor_eval 4y 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".
- xvello 4y agoFor 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.
- doctor_eval 4y agoWhile true, this approach doesn’t work for nested structs, which are instantiated by the parser.
- icholy 4y agoWrite a DefaultFoo function which returns a Foo with default values set. Then unmarshal into that.