1. studentMap := make(map[string]map[string]string)
  2. fmt.Printf("studentMap 类型: %T, 值: %v \n", studentMap, studentMap)
  3. studentMap["01"] = make(map[string]string)
  4. studentMap["01"]["name"] = "xiao"
  5. studentMap["01"]["sex"] = "男"
  6. studentMap["02"] = make(map[string]string)
  7. studentMap["02"]["name"] = "xiao"
  8. studentMap["02"]["sex"] = "男"
  9. studentMap["02"]["addr"] = "上海"
  10. fmt.Println("studentMap = ", studentMap)
  11. // studentMap = map[01:map[name:xiao sex:男] 02:map[addr:上海 name:xiao sex:男]]

增加、修改

  1. map[key] = value // 不存在key就是新增,存在就是修改

删除

func delete(m map[Type]Type1, key Type)
内建函数delete按照指定的键将元素从映射中删除。若m为nil或无此元素,delete不进行操作。

  1. // 删除 studentMap["02"]["addr"]
  2. delete(studentMap["02"], "addr")
  3. fmt.Printf("studentMap[02] = %v \n", studentMap["02"])
  4. // studentMap[02] = map[name:xiao sex:男]
  5. var bookMap map[string]string = map[string]string{
  6. "01": "Golang",
  7. "02": "GoWeb",
  8. }
  9. fmt.Println("bookMap = ", bookMap)
  10. bookMap = make(map[string]string) // bookMap = map[01:Golang 02:GoWeb]
  11. fmt.Println("bookMap = ", bookMap) // bookMap = map[]
  • 只可以一个一个的删除,
  • 可以遍历所有的key,逐个删除
  • 重新赋值 map = make(…) make一个新的,让原来的成为垃圾,被gc回收

查找

  1. // 查找
  2. val, ok := bookMap["03"]
  3. // 返回两个值,一个是key对应的value, 另一个是否有这个key
  4. if ok {
  5. fmt.Printf("存在bookMap[01], 值为: %v \n", val)
  6. } else {
  7. fmt.Println("不存在bookMap[01]")
  8. }

遍历map

for range 遍历map,获取到的值就是 key, value

单层map遍历

  1. // for range 遍历map
  2. var bookMap01 map[string]string = map[string]string{
  3. "01": "Golang",
  4. "02": "GoWeb",
  5. }
  6. for k, v := range bookMap01 {
  7. fmt.Printf("k = %v, v= %v \n", k, v)
  8. }
  9. // k = 01, v= Golang
  10. // k = 02, v= GoWeb

双层map遍历

  1. studentMap := make(map[string]map[string]string)
  2. fmt.Printf("studentMap 类型: %T, 值: %v \n", studentMap, studentMap)
  3. studentMap["01"] = make(map[string]string)
  4. studentMap["01"]["name"] = "xiao"
  5. studentMap["01"]["sex"] = "男"
  6. studentMap["02"] = make(map[string]string)
  7. studentMap["02"]["name"] = "xiao"
  8. studentMap["02"]["sex"] = "男"
  9. studentMap["02"]["addr"] = "上海"
  10. fmt.Println("studentMap = ", studentMap)
  11. for k1, v1 := range studentMap {
  12. fmt.Println("k1 = ", k1)
  13. for k2, v2 := range v1 {
  14. fmt.Printf("\t%v[%v] = %v \n", k1, k2, v2)
  15. }
  16. fmt.Println()
  17. }
  18. // 输出
  19. k1 = 01
  20. 01[name] = xiao
  21. 01[sex] =
  22. k1 = 02
  23. 02[name] = xiao
  24. 02[sex] =

map的长度

func len(v Type) int
内建函数len返回 v 的长度,这取决于具体类型:

  • 数组:v中元素的数量
  • 数组指针:*v中元素的数量(v为nil时panic)
  • 切片、映射:v中元素的数量;若v为nil,len(v)即为零
  • 字符串:v中字节的数量
  • 通道:通道缓存中队列(未读取)元素的数量;若v为 nil,len(v)即为零