定义MAP

  1. 可以使用内建函数make也可以使用map关键字定义Map:
  1. /* 声明变量,默认 map 是 nil */
  2. var map_variable map[key_data_type]value_data_type
  3. /* 使用 make 函数 */
  4. map_variable = make(map[key_data_type]value_data_type)

如果不初始化map,那么就会创建一个nil map。nil map不能用来存储键值对。

实例

  1. package main
  2. import "fmt"
  3. func main() {
  4. var countryCapitalMap map[string]string
  5. /* 创建集合 */
  6. countryCapitalMap = make(map[string]string)
  7. /* map 插入 key-value 对,各个国家对应的首都 */
  8. countryCapitalMap["France"] = "Paris"
  9. countryCapitalMap["Italy"] = "Rome"
  10. countryCapitalMap["Japan"] = "Tokyo"
  11. countryCapitalMap["India"] = "New Delhi"
  12. /* 使用 key 输出 map 值 */
  13. for country := range countryCapitalMap {
  14. fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  15. }
  16. /* 查看元素在集合中是否存在 */
  17. captial, ok := countryCapitalMap["United States"]
  18. /* 如果 ok 是 true, 则存在,否则不存在 */
  19. if(ok){
  20. fmt.Println("Capital of United States is", captial)
  21. }else {
  22. fmt.Println("Capital of United States is not present")
  23. }
  24. }

以上实例运行结果为:

  1. Capital of France is Paris
  2. Capital of Italy is Rome
  3. Capital of Japan is Tokyo
  4. Capital of India is New Delhi
  5. Capital of United States is not present

delete()函数

  1. delete()函数用于删除集合的元素,参数为map和其对应的key。实例如下:
  1. package main
  2. import "fmt"
  3. func main() {
  4. /* 创建 map */
  5. countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
  6. fmt.Println("原始 map")
  7. /* 打印 map */
  8. for country := range countryCapitalMap {
  9. fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  10. }
  11. /* 删除元素 */
  12. delete(countryCapitalMap,"France");
  13. fmt.Println("Entry for France is deleted")
  14. fmt.Println("删除元素后 map")
  15. /* 打印 map */
  16. for country := range countryCapitalMap {
  17. fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  18. }
  19. }

运行结果

  1. 原始 map
  2. Capital of France is Paris
  3. Capital of Italy is Rome
  4. Capital of Japan is Tokyo
  5. Capital of India is New Delhi
  6. Entry for France is deleted
  7. 删除元素后 map
  8. Capital of Italy is Rome
  9. Capital of Japan is Tokyo
  10. Capital of India is New Delhi

Golang Map - 图1