4 ms·
A map is a pointer to the actual map implementation. When declared via var m map[T]T you're basically writing var m *runtime.hmap which is a nil poi
by barsonme 10y ago
A map is a pointer to the actual map implementation. When declared via
var m map[T]T
you're basically writing
var m *runtime.hmap
which is a nil pointer. Go has sane zero values, so it makes sense that reading from a nil map returns the zero value for whatever type its values are.
However, there's a trade-off: either Go's maps allow nil assignment (in a similar fashion to slice's `append') _or_ it retains its "reference" (forgive me for using that term) semantics.
Go's designers decided that maps should differ from slices in that regard, and I tend to agree. I think it'd be a mistake to have to always return a map _just_ in it's newly allocated.