Are maps passed by value or reference in Go ?
It is always possible to define a function as following, but is this an overkill ?
func foo(dat *map[string
Here are some parts from If a map isn’t a reference variable, what is it? by Dave Cheney:
A map value is a pointer to a
runtime.hmap
structure.
and conclusion:
Conclusion
Maps, like channels, but unlike slices, are just pointers to runtime types. As you saw above, a map is just a pointer to a
runtime.hmap
structure.Maps have the same pointer semantics as any other pointer value in a Go program. There is no magic save the rewriting of map syntax by the compiler into calls to functions in
runtime/hmap.go
.
And an interesting bit about history/explanation of map
syntax:
If maps are pointers, shouldn’t they be
*map[key]value
?It’s a good question that if maps are pointer values, why does the expression
make(map[int]int)
return a value with the typemap[int]int
. Shouldn’t it return a*map[int]int
? Ian Taylor answered this recently in a golang-nuts thread1.In the very early days what we call maps now were written as pointers, so you wrote
*map[int]int
. We moved away from that when we realized that no one ever wrotemap
without writing*map
.Arguably renaming the type from
*map[int]int
tomap[int]int
, while confusing because the type does not look like a pointer, was less confusing than a pointer shaped value which cannot be dereferenced.