目录
结构
- map
// Map contains Type fields specific to maps.
type Map struct {
Key *Type // Key type
Elem *Type // Val (elem) type
Bucket *Type // internal struct type representing a hash bucket
Hmap *Type // internal struct type representing the Hmap (map header object)
Hiter *Type // internal struct type representing hash iterator state
}
对外表现的类型Map,所有的field都是指针型
- hmap - a header for a Go map
// A header for a Go map
type hmap struct {
count int // # live cells == size of map. Must be first (used by len() builtin)
flags uint8 //0- 1-there may be an iterator using buckets 2 - there may be an iterator using oldbuckets 4 - a goroutine is writing to the map 8 - the current map growth is to a new map of the same size
B uint8 // 桶的数量2^B, log_2 of # of buckets (can hold up to loadFactor * 2^B items)
noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
hash0 uint32 // hash seed
buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0. hiter
oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated)
extra *mapextra // optional fields,存储溢出信息
}
- count为函数len()的值 ,所以len时间复杂度为O(1)
- flags用于标记当前map的状态 —— 0 -> 正常;1 -> 有迭代器正在使用buckets,buckets为结构里第6个field;2 -> 有迭代器正在使用oldbuckets, oldbuckets为第7个field;4 -> 有goroutine正在往里写数据;8 -> 当成map正在扩展成一个相同尺寸的map
-
B,桶个数,2^B个桶
-
noverflow,(number of overflow),overflow桶的大致数量
-
hash0, hash种子
-
buckets,存放map键值对,是一个bucket数组,当count=0时这个值为nil
-
oldbuckets,上面buckets数量的一半,map增长的时候使用,不在增长期时为nil
-
nevacuate,(number of evacuate),map增长的时候使用
- extra,存储溢出信息,结构如下,当buckets空间使用完后并不会马上扩空间,会允许存放一定量的键值对到mapextra里
// mapextra holds fields that are not present on all maps.
type mapextra struct {
overflow *[]*bmap
oldoverflow *[]*bmap
// nextOverflow holds a p