-
Notifications
You must be signed in to change notification settings - Fork 1
/
map.go
51 lines (40 loc) · 811 Bytes
/
map.go
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import "fmt"
func logMap(m map[string]int) {
for key, val := range m {
fmt.Println(key, val)
}
// loop map with only value
for _, val := range m {
fmt.Println(val)
}
// loop map with only key
for key := range m {
fmt.Println(key)
}
}
func TestExist(m map[string]int, key string) {
// the second param is true/false if key is existen in map
val, exist := m[key]
fmt.Println(val, exist)
}
func main() {
// Create new map string -> int
m := make(map[string]int)
m["a"] = 10
m["b"] = 20
m["c"] = 30
logMap(m)
TestExist(m, "a") // 10, true
TestExist(m, "t") // 0, false
// Remove key "a" from map m
delete(m, "a")
TestExist(m, "a") // 0, false
// initialize map string -> int without make()
m = map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
fmt.Println(m)
}