Something I’ve noticed as a Go novice that I’d like an explanation on:
Let’s say I have a map that I pass by reference to a function
myMap := make(map[string]int)
myFunc(&myMap)
Inside of the func, I have to copy that map to a local variable in the function, modify that, then re-copy it before the map that I want to modify is actually modified:
causes my IDE to complain in both instances that I can’t index a pointer to a map.
What is the cause of this? I understand that there could be issues with concurrent writes, but that would be the case with other variables that I can do this with. This is a very interesting problem to me, and I’d love to know what’s going on under the hood.
maps are a special data type, they are not a struct, nor a pointer to a struct (pointer to a runtime.hmap object), but something close to that.
Every time you use a map, at compile time your map-related code will be replaced by auto generated code. This creates limitations into how you can work with maps (and how you should think about them).
@Yamil_Bracho gave the right answer, use (*tMap)[“Gander”] = 14
On the other hand using pointers on maps is not such a good idea because:
Of all of Go’s built in data structures, maps are the only ones that move data internally. When you insert or delete entries, the map may need to rebalance itself to retain its O(1) guarantee. This is why map values are not addressable .