map 类型
基础知识
map[string]uint32m := make(map[string]uint32)commits := map[string]int{ "rsc": 3711, "r": 2138, "gri": 1908, "adg": 912,}
m["route"] = 66i := m["route"]
l := len(m)
delete(m, "route")
_, ok := m["route"] // if exists, true
for key, value := range m { fmt.Println("Key:", key, "Value:", value)}
常规用法
- key 不存在时,返回 value 类型默认值;map[KeyType]bool 当作集合使用
type Node struct { Next *Node Value interface{}}var first *Nodevisited := make(map[*Node]bool)for n := first; n != nil; n = n.Next { if visited[n] { fmt.Println("cycle detected") break } visited[n] = true fmt.Println(n.Value)}
type Person struct { Name string Likes []string}var people []*Personlikes := make(map[string][]*Person) // slice is nilfor _, p := range people { for _, l := range p.Likes { likes[l] = append(likes[l], p) }}
func add(m map[string]map[string]int, path, country string) { mm, ok := m[path] if !ok { mm = make(map[string]int) m[path] = mm } mm[country]++}add(hits, "/doc/", "au")
type Key struct { Path, Country string}hits := make(map[Key]int)
var counter = struct{ sync.RWMutex m map[string]int}{m: make(map[string]int)}counter.RLock()n := counter.m["some_key"]counter.RUnlock()counter.Lock()counter.m["some_key"]++counter.Unlock()