1. map基础
1.1. key类型限制
在golang中,map的key必须是可以支持==
比较的数据类型:
2. map深入
2.1. map的原理
golang的map
是一个hash表,利用拉链法解决哈希冲突,map底层数据结构由一个结构体hmap
实现:
// A header for a Go map.
type hmap struct {
// Note: the format of the hmap is also encoded in cmd/compile/internal/reflectdata/reflect.go.
// Make sure this stays in sync with the compiler's definition.
count int // # live cells == size of map. Must be first (used by len() builtin)
flags uint8
B uint8 // 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.
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
: map元素数量flags
: map当前状态标志
const(
// ...
// flags
iterator = 1 // there may be an iterator using buckets
oldIterator = 2 // there may be an iterator using oldbuckets
hashWriting = 4 // a goroutine is writing to the map
sameSizeGrow = 8 // the current map growth is to a new map of the same size
// ...
)
B
: bucket 数量的对数, N ( b u c k e t ) = 2 B N(bucket)=2^{B} N(bucket)=2Bnoverflow
: 出现溢出的 bucket 的数量的估计值hash0
: 哈希种子buckets
: bucket 数组指针oldbuckets
: 旧 bucket 数组指针nevacuate
: 迁移进度extra
: …