Are maps passed by value or by reference in Go?

前端 未结 3 1802
北恋
北恋 2021-01-30 05:10

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         


        
3条回答
  •  失恋的感觉
    2021-01-30 05:32

    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 type map[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 wrote map without writing *map.

    Arguably renaming the type from *map[int]int to map[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.

提交回复
热议问题