當你聲明一個map的時候:
m := make(map[int]int)
編譯器會調用 runtime.makemap:
// makemap implements a Go map creation make(map[k]v, hint)
// If the compiler has determined that the map or the first bucket
// can be created on the stack, h and/or bucket may be non-nil.
// If h != nil, the map can be created directly in h.
// If bucket != nil, bucket can be used as the first bucket.
func makemap(t *maptype, hint int64, h *hmap, bucket unsafe.Pointer) *hmap
所以實際上是返回一個hmap的指針。
如何驗證呢?
func main(){
m := make(map[int]int)
m[1] = 1
fmt.Printf("原始map的內存地址是:%p\n", m)
modify(m)
fmt.Println("map值被修改了,新值為:", m)
}
func modify(m interface{}){
fmt.Printf("函數里接收到map的內存地址是:%p\n", p)
m := p.(map[int]int)
m[1] = 2
}
輸出結果:
原始map的內存地址是:0xc00009e030
函數里接收到map的內存地址是:0xc00009e030
map值被修改了,新值為: map[1:2]
在main函數中,m是個指針變量,它保存的值是:0xc00009e030。
在modify函數中,m也是個指針變量,保存的值也是:0xc00009e030。
說明初始化map后,返回的是指針變量,在函數之間,傳遞的是map的地址。
map和channel是相似的。
那么為什么不是 *map[key]value呢,這樣不是更直觀?
Ian Taylor answered this recently in a golang-nuts 原話是:
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
mapwithout writing\*map.
意思是,一開始也是寫作 *map[key]value,后來發現所有的map都是當作指針來用的,於是就省略簡寫了。
