3 ms·
How do you distinguish between a value set to zero value explicitly, and one not set?
by EdwardDiego 2y ago
How do you distinguish between a value set to zero value explicitly, and one not set?
- jochem9 2y agoThere is no difference. You need to handle that based on the context you're in.
- EdwardDiego 2y agoI was wondering if there's a pattern of using Option types or something to signal the difference. I ask because I hit this issue a fair few years ago with protobuf v3, we ended up using a wrapper type pattern. Can't recall why it was important to know at the time, but it was.
- the_gipsy 2y agoSometimes you can abuse pointers as a (very) poor man's Option<T> type. But it's turtles all the way down, you can't distinguish between for example `null` and "missing" when parsing JSON.
- mervz 2y agoYikes...
- kzs0 2y agoIn the cases where this is important, you can use pointers. Go allows you to make pointers to primitives as well (making the zero value nil) so you can explicitly define those edge cases. You’d be surprised how infrequently that’s actually a concern though.
- deergomoo 2y agoUsing pointers feels horrible as a workaround though because it completely muddies the intent. Is it a pointer because it could be zero or <not set>, is it a pointer for performance reasons, is it a pointer because the function mutates it? To me it flies directly in the face of Go's desire to keep things simple and easy to reason about. > You’d be surprised how infrequently that’s actually a concern though I admittedly don't write a huge amount of Go, but I run into this fairly often any time I'm dealing with user input. Something like an optional numeric input is not at all uncommon.
- metaltyphoon 2y agoHow do you have a PUT on an API to “unset a field”?
- Neikius 2y agoWhat? That is actually an everyday concern and devs assuming that information is not needed will bring pain down the road. Just two cases of the top of my head: working with databases and json interop with other systems that actually do differentiate. And the second one should not happen, but people do make assumptions and sometimes those are inherently incompatible with how golang works.