社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
// 1. 声明
var m map[string]int
// 2. 初始化,声明之后必须初始化才能使用
// 向未初始化的map赋值引起 panic: assign to entry in nil map.
m = make(map[string]int)
m = map[string]int{}
// 1&2. 声明并初始化
m := make(map[string]int)
m := map[string]int{}
// 3. 增删改查
m["route"] = 66
delete(m, "route") // 如果key不存在什么都不做
i := m["route"] // 三种查询方式,如果key不存在返回value类型的零值
i, ok := m["route"]
_, ok := m["route"]
// 4. 迭代(顺序不确定)
for k, v := range m {
use(k, v)
}
// 5. 有序迭代
import "sort"
var keys []string
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
use(k, m[k]
}
The key can be any type for which the equality operator is defined.
// 声明&初始化
var counter = struct {
sync.RWMutex // gard m
m map[string]int
}{m:make(map[string]int)}
// 读锁
counter.RLock()
counter.m["route"]
counter.RUnlock()
// 写锁
counter.Lock()
counter.m["route"]++
counter.Unlock()
visited := map[*Node]bool
if visited[node] { // bool类型0值为false,所以不需要检查ok
return
}
likes := make(map[string][]*Person)
for _, p range people {
for _, l range p.Likes {
// 向一个nil的slice增加值,会自动allocate一个slice
likes[l] = append(likes[l], p)
}
}
// map[k1]map[k2]v
hits := make(map[string]map[string]int)
func add(m map[string]map[string]int, path, country string) {
mm, ok := m[path]
if !ok {
mm = make(map[string]int) // 需要检查、创建子map
m[path] = mm
}
mm[country]++
}
add(hits, "/", "cn")
n := hits["/"]["cn"]
// map[struct{k1, k2}]v
type Key struct {
Path, Country string
}
hits := make(map[Key]int)
hits[Key{"/", "cn"}]++
n := hits[Key{"/", "cn"}]
}
golang为每个类型定义了类型描述器_type
,并实现了hashable类型的_type.alg.hash
和_type.alg.equal
。
type typeAlg struct {
// function for hashing objects of this type
// (ptr to object, seed) -> hash
hash func(unsafe.Pointer, uintptr) uintptr
// function for comparing objects of this type
// (ptr to object A, ptr to object B) -> ==?
equal func(unsafe.Pointer, unsafe.Pointer) bool
}
hash & (uintptr(1)<<h.B - 1)
计算出key所在bucket的index; tophash [bucketCnt]uint8
,它保存了key的hash值的高8位uint8(hash >> (sys.PtrSize*8 - 8))
;一个bucket包括一个bmap(tophash数组),紧跟的bucketCnt个keys和bucketCnt个values,以及一个overfolw指针。
func makemap(t *maptype, hint int64, h *hmap, bucket unsafe.Pointer) *hmap {
...
// initialize Hmap
if h == nil {
h = (*hmap)(newobject(t.hmap))
}
h.count = 0
h.B = B
h.flags = 0
h.hash0 = fastrand()
h.buckets = buckets
h.oldbuckets = nil
h.nevacuate = 0
h.noverflow = 0
return h
}
golang的maptype保存了key的类型描述器,以供访问map时调用key.alg.hash
, key.alg.equal
。
type maptype struct {
key *_type
elem *_type
...
}
func mapaccess1(t *maptype, h *hmap, key unsafe.Pointer) unsafe.Pointer {
...
// 并发访问检查
if h.flags&hashWriting != 0 {
throw("concurrent map read and map write")
}
// 计算key的hash值
alg := t.key.alg
hash := alg.hash(key, uintptr(h.hash0)) // alg.hash
// 计算key所在的bucket的index
m := uintptr(1)<<h.B - 1
b := (*bmap)(add(h.buckets, (hash&m)*uintptr(t.bucketsize)))
// 计算tophash
top := uint8(hash >> (sys.PtrSize*8 - 8))
...
for {
for i := uintptr(0); i < bucketCnt; i++ {
// 检查top值
if b.tophash[i] != top {
continue
}
// 取key的地址
k := add(unsafe.Pointer(b), dataOffset+i*uintptr(t.keysize))
if alg.equal(key, k) { // alg.equal
// 取value得地址
v := add(unsafe.Pointer(b), dataOffset+bucketCnt*uintptr(t.keysize)+i*uintptr(t.valuesize))
}
}
...
if b == nil {
// 返回零值
return unsafe.Pointer(&zeroVal[0])
}
}
}
这部分留待以后有机会再续。这里暂时附上Keith Randall的slide作为参考。
make(map[int]int, 1000)
for k:= range m { delete(m, k) }
https://blog.csdn.net/Soooooooo8/article/details/70163475
参考
Go msps in action
hashmap.go type.go
GopherCon 2016: Keith Randall - Inside the Map Implementation
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!