4 ms·
But many types do have a "natural" zero value, that you may want to use, beyond just the numbers. Consider the empty string, empty list, empty dictionary, empty
by Jtsummers 5y ago
But many types do have a "natural" zero value, that you may want to use, beyond just the numbers. Consider the empty string, empty list, empty dictionary, empty set. Those are zero values for their types. By reserving them as pseudo-nulls you lose the ability to distinguish between an object which happens to be empty and an object which is meant to mean "null". This is where Optional (or similar mechanisms) come in handy. If you actually want to avoiding creating null, Optional is a cleaner and more consistent way to accomplish this without needing to magic up a null-value in your type's valid set of values or create a one-off Optional (MaybeDictionary, MaybeList).
- saghm 5y agoIt's even worse than that in my opinion: the zero value for maps and slices is actually nil even though they're not pointers, meaning the empty values are not the zero values. This lets you do "fun" things like this (my memory of the syntax might be slightly off): ``` var map1 map[int]int = nil var map2 map[int]int = &map1 var map3 map[int]int = nil ``` Interface types also can be nil even if they're not explicitly pointers because heap pointers are needed under the hood due to the size of the value not being knowable at compile time. You can pretty quickly get into some hairy situations trying to ensure that a value isn't nil when combining pointers or maps/slices with interfaces. I really wish that separating the concerns of present versus not present from value versus reference was more mainstream. I understand why this was traditionally the case for lower-level languages, but even higher-level ones like Java are mostly based on the paradigm that only references can be "not present". This irks me in a similar way to how earlier versions of Java wouldn't allow default implementations of interface methods and instead requiring abstract classes, which classes could not extend from more than one of.