In Go, a map is essentially a pointer to a data structure.

A zero-valued map is thus like a zero-valued pointer. You would not expect

var ap *int

to allocate space for an int up-front; nor for

*ap = 1

to allocate an int  (and change ap to point to it) if ap is nil.

Like pointers, maps are passed by value.  So if you passed a nil map to a 
function, and the function dynamically allocated a map when inserting the 
first value, the caller would be no wiser; they'd still be holding a nil 
map. You'd have to return the new map, or pass a pointer to the original 
variable holding the map.

In a functional programming language, a map would be immutable and you'd 
always return a new map value in order to update it. That's cool, but it's 
not really Go's style.

Passing a pointer to a map is doable, but means special-casing 
<https://go.dev/play/p/0Xa0lqbhf3s> wherever you want to do updates:

func foo(m *map[string]string) {
if *m == nil {
*m = make(map[string]string)
}
(*m)["foo"] = "bar"
}

I guess you could wrap this pattern: https://go.dev/play/p/VdH1W-Y5Dky
(I couldn't be bothered to try using generics). But in any case, it 
involves passing a pointer to a map everywhere, which means an extra level 
of indirection for every map access.

IMO it's simpler to say: "if you're passing a map into a function, and this 
function might modify the map, then the caller must allocate it first".  
Note: passing a nil map to a function is still valid if you only expect it 
to read from the map, not update it.

Once a map has been allocated, its value doesn't change, so you can happily 
pass it around by value. The data structure changes as items are inserted 
and removed, but its location doesn't change, and the map value is just a 
pointer to that location.

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/9494683b-6d4d-457b-b913-156139d92e63n%40googlegroups.com.

Reply via email to