Go 语言Map

最后编辑于2019-10-12 11:31:14 +0800 CST

Map 是一种无序的键值对的集合。Map 最重要的一点是通过 key 来快速检索数据,key 类似于索引,指向数据的值。

Map 是一种集合,所以我们可以像迭代数组和切片那样迭代它。不过,Map 是无序的,我们无法决定它的返回顺序,这是因为 Map 是使用 hash 表来实现的。


定义 Map

可以使用内建函数 make 也可以使用 map 关键字来定义 Map:

go
1/* 声明变量,默认 map 是 nil */
2var map_variable map[key_data_type]value_data_type
3
4/* 使用 make 函数 */
5map_variable = make(map[key_data_type]value_data_type)

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

下面实例演示了创建和使用map:

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

以上实例运行结果为:

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

delete() 函数

delete() 函数用于删除集合的元素, 参数为 map 和其对应的 key。实例如下:

go
 1package main
 2
 3import "fmt"
 4
 5func main() {   
 6   /* 创建 map */
 7   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
 8   
 9   fmt.Println("原始 map")   
10   
11   /* 打印 map */
12   for country := range countryCapitalMap {
13      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
14   }
15   
16   /* 删除元素 */
17   delete(countryCapitalMap,"France");
18   fmt.Println("Entry for France is deleted")  
19   
20   fmt.Println("删除元素后 map")   
21   
22   /* 打印 map */
23   for country := range countryCapitalMap {
24      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
25   }
26}

以上实例运行结果为:

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