map 类型

基础知识

  • map[KeyType]ValueType
  1. map[string]uint32
  2. m := make(map[string]uint32)
  3. commits := map[string]int{
  4. "rsc": 3711,
  5. "r": 2138,
  6. "gri": 1908,
  7. "adg": 912,
  8. }
  • 访问
  1. m["route"] = 66
  2. i := m["route"]
  • 长度
  1. l := len(m)
  • 删除
  1. delete(m, "route")
  • key 是否存在
  1. _, ok := m["route"] // if exists, true
  • 遍历
  1. for key, value := range m {
  2. fmt.Println("Key:", key, "Value:", value)
  3. }

常规用法

  • key 不存在时,返回 value 类型默认值;map[KeyType]bool 当作集合使用
  1. type Node struct {
  2. Next *Node
  3. Value interface{}
  4. }
  5. var first *Node
  6. visited := make(map[*Node]bool)
  7. for n := first; n != nil; n = n.Next {
  8. if visited[n] {
  9. fmt.Println("cycle detected")
  10. break
  11. }
  12. visited[n] = true
  13. fmt.Println(n.Value)
  14. }
  • 配合 slice
  1. type Person struct {
  2. Name string
  3. Likes []string
  4. }
  5. var people []*Person
  6. likes := make(map[string][]*Person) // slice is nil
  7. for _, p := range people {
  8. for _, l := range p.Likes {
  9. likes[l] = append(likes[l], p)
  10. }
  11. }
  • 配合 map
  1. func add(m map[string]map[string]int, path, country string) {
  2. mm, ok := m[path]
  3. if !ok {
  4. mm = make(map[string]int)
  5. m[path] = mm
  6. }
  7. mm[country]++
  8. }
  9. add(hits, "/doc/", "au")
  • key 类型为 struct
  1. type Key struct {
  2. Path, Country string
  3. }
  4. hits := make(map[Key]int)
  • 并发情况下使用
  1. var counter = struct{
  2. sync.RWMutex
  3. m map[string]int
  4. }{m: make(map[string]int)}
  5. counter.RLock()
  6. n := counter.m["some_key"]
  7. counter.RUnlock()
  8. counter.Lock()
  9. counter.m["some_key"]++
  10. counter.Unlock()