【Go】map详解

Perl有哈希、Python有字典、C++有map库、go也有map类型, 这些都是类似的

定义map的方法:

map[<key_type>]<value_type>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 注意尾部逗号也是必须的
monthday := map[string]int{
"Jan": 31,
"Feb": 28,
"Mar": 31,
"Apr": 30,
"May": 31,
"Jun": 30,
"Jul": 31,
"Aug": 31,
"Sep": 30,
"Oct": 31,
"Nov": 30,
"Dec": 31,
}

用make创建动态map

1
monthdays := make(map[string]int)

对map进行索引访问

1
monthdays["Jul"]

对map进行遍历访问

可以使用到之前讲的range

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
30
31
32
33
34
35
package main
import (
"fmt"
)

func main() {
monthdays := map[string]int{
"Jan": 31,
"Feb": 28,
"Mar": 31,
"Apr": 30,
"May": 31,
"Jun": 30,
"Jul": 31,
"Aug": 31,
"Sep": 30,
"Oct": 31,
"Nov": 30,
"Dec": 31,
}

year := 0
for mon, days := range monthdays {
year += days
fmt.Printf("%s = %d\n", mon, days)
}

fmt.Printf("Days of one year: %d\n", year)

new_year := 0
for _, days := range monthdays {
new_year += days
}
fmt.Printf("Days of one new year: %d\n", new_year)
}

保存为hellowrold.go,然后执行查看结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[me@VM_0_14_centos go]# go run helloworld.go 
Oct = 31
Mar = 31
Jul = 31
Aug = 31
Sep = 30
Jun = 30
Nov = 30
Dec = 31
Jan = 31
Feb = 28
Apr = 30
May = 31
Days of one year: 365
Days of one new year: 365

向map追加元素

1
2
3
4
5
6
7
// 添加未知月份的天数为 0
monthdays["unknown"] = 0

#### 从map删除元素
```go
// 注意到,delete是之前文章提到的内建函数
delete(monthdays, "Dec")

检测键值是否存在

通过双赋值来检测键值是否存在

1
2
// 如果key存在monthdays,则 ok为true,否则 ok为false
mon, ok := monthdays[key]

坚持原创技术分享,谢谢鼓励我继续创作!