map是一种无序的基于key-value的数据结构,Go语言中的map是引用类型,必须初始化才能使用

1.map基本使用

  1. map[KeyType]ValueType
  2. KeyType:表示键的类型。
  3. ValueType:表示键对应的值的类型。
  1. m := make(map[string]int,8)
  2. m["k1"] = 10
  3. m["k2"] = 20
  4. fmt.Println(m)
  5. fmt.Println(m["k1"])
  1. user :=map[string]string{
  2. "username":"cheng",
  3. "password":"wdnmd",
  4. }
  5. fmt.Println(user)

2.判断某个键是否存在

  1. value, ok := map[key]
  1. m := make(map[string]int,8)
  2. m["k1"] = 10
  3. m["k2"] = 20
  4. value,ok :=m["k1"]
  5. if ok {
  6. fmt.Println(value)
  7. }else {
  8. fmt.Println("没有")
  9. }

3.map的遍历

  1. m := make(map[string]int,8)
  2. m["k1"] = 10
  3. m["k2"] = 20
  4. m["k3"] = 30
  5. m["k4"] = 40
  6. m["k5"] = 50
  7. for k, v := range m {
  8. fmt.Println(k,v)
  9. }

4.使用delete()函数删除键值对

使用delete()内建函数从map中删除一组键值对

  1. delete(map, key)
  2. map:表示要删除键值对的map
  3. key:表示要删除的键值对的键
  1. m := make(map[string]int)
  2. m["k1"] = 10
  3. m["k2"] = 20
  4. m["k3"] = 30
  5. m["k4"] = 40
  6. m["k5"] = 50
  7. delete(m,"k1")
  8. fmt.Println(m) //map[k2:20 k3:30 k4:40 k5:50]

5.按照指定顺序遍历map

  1. var m = make(map[string]int,200)
  2. for i := 0; i < 100; i++ {
  3. key := fmt.Sprintf("stu%02d", i)
  4. value := rand.Intn(100)
  5. m[key] = value
  6. }
  7. for k, v := range m {
  8. fmt.Println(k,v)
  9. }
  10. //无序
  11. stu00 81
  12. stu03 59
  13. stu01 87
  14. stu07 40
  15. stu09 0
  16. stu05 18
  17. stu08 56
  18. stu06 25
  19. stu02 47
  20. stu04 81
  1. var m = make(map[string]int,20)
  2. for i := 0; i < 10; i++ {
  3. key := fmt.Sprintf("stu%02d", i
  4. value := rand.Intn(100)
  5. m[key] = value
  6. }
  7. var keys = make([]string,0,10)
  8. for key, _ := range m {
  9. keys=append(keys, key)
  10. }
  11. sort.Strings(keys)
  12. //按照排序后的key遍历map
  13. for _, key := range keys {
  14. fmt.Println(key,m[key])
  15. }

6.元素为map类型的切片

  1. var slice = make([]map[string]string,3)
  2. for index, value:= range slice {
  3. fmt.Println(index,value)
  4. }
  5. //0 map[]
  6. //1 map[]
  7. //2 map[]
  1. var slice = make([]map[string]string,3)
  2. for index, value:= range slice {
  3. fmt.Println(index,value)
  4. }
  5. //对切片中的map元素进行初始化
  6. slice[0] = make(map[string]string,10)
  7. slice[0]["name"] = "cheng"
  8. slice[0]["password"] = "123456"
  9. fmt.Println(slice[0])

7.值为切片类型的map

  1. var m = make(map[string][]string,3)
  2. fmt.Println(m)
  3. key := "中国"
  4. value,ok :=m[key]
  5. if !ok {
  6. value = make([]string,0,2)
  7. }
  8. value=append(value,"香港","台湾")
  9. m[key] = value
  10. fmt.Println(m)