map不会是引用变量,那是什么?

golang精选博文翻译仓库
在之前文章,go中没有引用,我们阐述了go与引用变量,以及go中没有引用传值。但是给我们留下了一个悬念,那就是map如果不是引用变量,那它是什么?

开门见山:map是一个指向runtime.hmap结构的指针

如果你还有疑问的话,请继续阅读下去。

map类型是什么

当我们这样声明的时候。

m := make(map[int]int)

编译器将其替换为调用 map.go/makemap

// makemap implements Go map creation for 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 h.buckets != nil, bucket pointed to can be used as the first bucket.
func makemap(t *maptype, hint int, h *hmap) *hmap 

可以看到,makemap函数返回*hmap,一个指向hmap结构的指针,我们可以从go源码中看到这些,除此之外,我们还可以证明map值的大小和uintptr一样。

package main

import (
	"fmt"
	"unsafe"
)

func main() {
	var m map[int]int
	var p uintptr
	fmt.Println(unsafe.Sizeof(m), unsafe.Sizeof(p)) // 8 8 (linux/amd64)
}

如果map是指针的话,它不应该返回*map[key]value吗?

这是个好问题,为什么表达式make(map[int]int)返回一个map[int]int类型的结构?不应该返回*map[int]int吗?

Ian Taylor在这个回答中说:

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`.

所以说,是把*map[int]int重命名为map[int]int

原文地址:https://www.cnblogs.com/Jun10ng/p/12725669.html