基本使用

  • make(map[keyType]valueType)
  1. package main
  2. import "fmt"
  3. func main() {
  4. // map[keyType]valueType
  5. var m map[string]string
  6. m= make(map[string]string,5)
  7. m["name"]="luckyFang"
  8. m["address"]="ShanXi"
  9. fmt.Printf("%v\n",m)
  10. person :=map[string]string{
  11. "name":"jack",
  12. }
  13. fmt.Printf("%v\n",person)
  14. }

操作map

  • delete 删除元素
  • map 是引用传递的
  1. package main
  2. import "fmt"
  3. func change(m map[string]int) {
  4. m["ZhangSan"]=59
  5. }
  6. func main() {
  7. scoreMap:=make(map[string]int)
  8. // 添加元素
  9. scoreMap["LiHua"]=90
  10. scoreMap["XiaoMing"]=92
  11. scoreMap["LiLi"]=85
  12. fmt.Printf("%v\n",scoreMap)
  13. // 修改元素
  14. scoreMap["LiHua"]=60
  15. fmt.Printf("%v\n",scoreMap)
  16. // 删除元素
  17. delete(scoreMap,"LiLi")
  18. // map是引用传递
  19. change(scoreMap)
  20. // 遍历Map
  21. for name,score :=range scoreMap{
  22. fmt.Printf("name=%v,score=%d\n",name,score)
  23. }
  24. }
  1. map[LiHua:90 LiLi:85 XiaoMing:92]
  2. map[LiHua:60 LiLi:85 XiaoMing:92]
  3. name=LiHua,score=60
  4. name=XiaoMing,score=92
  5. name=ZhangSan,score=59