by ratorx · 2y ago · 0 comments
If “null” is better for your use case, that’s not too difficult to emulate in Go (although perhaps not as ergonomic as it is in other languages). What you want is effectively an “optional” type rather than the type itself. The easiest way to represent this in Go is to use pointers to the type, which have the zero-value of nil. Combining this with JSON encoding ‘omitempty’ would get you the properties you were looking for.
I don’t think the lack of default nullability is bad (look at all the languages that are trying to slowly phase it out by supporting non-nullable types).
You're right, I was referring to Javascript-style `undefined`, where it's basically a 2nd `null` value.
> The easiest way to represent this in Go is to use pointers to the type, which have the zero-value of nil.
This certainly works, but it has some serious drawbacks imo:
* Performance overhead
* The integer field is no longer copied along with the struct. The resulting aliasing shenanigans can easily trip up experienced developers, because "why would anyone store an `*int` in a struct instead of a plain `int`?"
* Other silly mistakes that no linters catch, such as comparing the pointers when you meant to compare the raw values.