【Go】Detailed map

Perl has hash, Python has dictionary, C ++ has map library, go also has map type, these are similar

Define map method:

map[<key_type>]<value_type>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Note that trailing commas are also required
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,
}

Create dynamic map with make

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

Index access to map

1
monthdays["Jul"]

Iterate over the map

You can use the range mentioned earlier

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)
}

Save as hellowrold.go, then execute to see the results

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

Append elements to the map

1
2
3
4
5
6
7
// add unknown days to 0
monthdays["unknown"] = 0

#### Remove elements from map
```go
// Notice that delete is a built-in function mentioned in the previous article
delete(monthdays, "Dec")

Detect if key exists

Detect the existence of key value by double assignment

1
2
// Ok is true if monthdays exists for the key, otherwise ok is false
mon, ok := monthdays[key]

Persist in original technology sharing, your support will encourage me to continue to create!