Currently, for optional fields in struct
go compiler generates the following:
which is wrong in multiple ways:
1. Freshly initialized fields returns IsSetField() true
This results in
a. wrong semantics: freshly created struct has optional fields set
b. excessive payload produced on serialization (writing field value instead of skipping it)
2. Additional load on garbage collector
3. accessing field value is complicated and error prone. even without default value:
would work for false default for field b. However, if I change default value to true, I need to change all occurrences in the code like this:
How to fix that?
there are two ways:
1. get back to generating inlines instead of pointers for optional fields with default value and compare with "magic value" of default in IsSet*(). could be tricky since not all types are comparable http://golang.org/ref/spec#Comparison_operators . notably, slices and maps are not.
2. approach, used in protobuf: Do not initialize optional fields, generate Get*() accessors like this:
Just to make API uniform, we can also generate accessors for required fields:
I'm inclining to implement second approach, but I would like to collect opinions before I dig into the code.