Golang 中 make(map[type1]type2) 的内部实现是什么?

What is internal implementation of make(map[type1]type2) in Golang?

Golang 是一种本地编程语言。所以比动态语言有很多限制(比如python和ruby)。

当将地图初始化为 m := make(Map[string]int) 时,此地图 m 似乎能够包含无限多个键值。

但是当用maps literal 初始化Maps 或者用cap make 时, maps 不能包含无穷多个key-values。

有些文章说make without cap会为这个map分配大量的内存。但这不是选项,因为如果它是 true,那么在初始化单个 map 时会消耗大量内存。但是不管我用什么电脑硬件监控工具,我的程序运行前和运行时内存是没有区别的。


func main(){
    Hello()
}

func Hello(){
    m := make(SizeRecord)
    l := 10000000
    for i := 0; i < l; i++ {
        m[strconv.Itoa(i)] = Size{float64(rand.Intn(100)), float64(rand.Intn(100)), float64(rand.Intn(100))}
    }

    fmt.Println(m)
}

程序需要一段时间才能执行。

我也看过一篇文章Go maps in action,里面说(不知道我理解的对不对)make without cap use an alternative implementation to represent map and use an unified interface to access the map与其他容量有限的地图一样。

如果我的理解有误,谁能告诉我什么是正确的?

如果我是对的,为什么golang没有这样实现所有的映射?

您对地图工作原理的理解不正确。规范说:

Blockquote The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

因此,容量只是一个提示,它会影响地图的初始大小。地图可以根据需要增长。具有给定容量的地图没有单独的实现。