二十、Go 语言 – 哈希表(map)

二十、Go 语言 – 哈希表(map)

map 又称哈希表,是一种一种无序的键值对的集合

map 最重要特点是通过 key 来快速检索数据,key 类似于索引,指向数据的值

Go 语言中的 map 也是一种集合,所以我们可以像迭代数组和切片那样迭代它

但在迭代时需要注意:map 是无序的,我们无法决定它的返回顺序,因为 map 是使用 hash 表来实现的

定义 map

1.使用内建函数 make 来定义 map

1
map_variable := make(map[key_data_type]value_data_type)

2. 使用 map 关键字来定义 map

这种方式声明的 map 默认是 nil

1
var map_variable map[key_data_type]value_data_type

如果不初始化 map,那么就会创建一个 nil map

nil map 不能用来存放键值对

范例

下面的范例演示了如何定义 map 和如何通过 键(key) 访问 map 中的元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main

import "fmt"

func main() {
var countryCapitalmap map[string]string
/* 创建集合 */
countryCapitalmap = make(map[string]string)

/* map 插入 key-value 对,各个国家对应的首都 */
countryCapitalmap["France"] = "Paris"
countryCapitalmap["Italy"] = "Rome"
countryCapitalmap["Japan"] = "Tokyo"
countryCapitalmap["India"] = "New Delhi"

/* 使用 key 输出 map 值 */
for country := range countryCapitalmap {
fmt.Println("Capital of",country,"is",countryCapitalmap[country])
}

/* 查看元素在集合中是否存在 */
captial, ok := countryCapitalmap["United States"]
/* 如果 ok 是 true, 则存在,否则不存在 */
if(ok){
fmt.Println("Capital of United States is", captial)
}else {
fmt.Println("Capital of United States is not present")
}
}

编译运行以上 Go 范例,输出结果如下

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