在开发过程中,map是必不可少的数据结构,在Golang中,使用map或多或少会遇到与其他语言不一样的体验,比如访问不存在的元素会返回其类型的空值、map的大小究竟是多少,为什么会报”cannot take the address of”错误,遍历map的随机性等等。
本文希望通过研究map的底层实现,以解答这些疑惑。
基于Golang 1.8.3
1. 数据结构及内存管理
hashmap的定义位于 src/runtime/hashmap.go 中,首先我们看下hashmap和bucket的定义:
type hmap struct {
count int // 元素的个数
flags