# 如何在 Go 中迭代整個 Map

Suraj Joshi 2023年1月30日

## 宣告和初始化 Map

``````var map_name map[KeyType]ValueType
``````

``````package main

import "fmt"

func main() {
map_1 := map[int]string{
0: "Alok",
1: "Reman",
2: "Riken",
3: "Rudra",
}

fmt.Println(map_1)
}
``````

``````map[0:Alok 1:Reman 2:Riken 3:Rudra]
``````

``````package main

import "fmt"

func main() {
var map_2 = make(map[int]string)
map_2[0] = "Alok"
map_2[1] = "Reman"
map_2[2] = "Riken"
map_2[3] = "Rudra"
fmt.Println(map_2)

}
``````

``````map[0:Alok 1:Reman 2:Riken 3:Rudra]
``````

## 遍歷 Go 中的 Map

### 遍歷 Go 中所有 map 的鍵和值

``````package main

import "fmt"

func main() {
map_1 := map[int]string{
0: "Alok",
1: "Reman",
2: "Riken",
3: "Rudra",
}

for k, v := range map_1 {
fmt.Printf("Key:%v Value: %s\n", k, v)
}

}
``````

``````Key:0 Value: Alok
Key:1 Value: Reman
Key:2 Value: Riken
Key:3 Value: Rudra
``````

``````package main

import "fmt"

func main() {
map_1 := map[string]string{
"Giri    ": "Alok",
"Nembang ": "Reman",
"Maharjan": "Riken",
"Jha     ": "Rudra",
}

for k, v := range map_1 {
fmt.Printf("Key:%v  Value: %s\n", k, v)
}

}

``````

``````Key:Giri      Value: Alok
Key:Nembang   Value: Reman
Key:Maharjan  Value: Riken
Key:Jha       Value: Rudra
``````

### 僅在 Go `map` 中迭代鍵

``````package main

import "fmt"

func main() {
map_1 := map[int]string{
0: "Alok",
1: "Reman",
2: "Riken",
3: "Rudra",
}

for k := range map_1 {
fmt.Printf("Key:%v\n", k)
}

}
``````

``````Key:0
Key:1
Key:2
Key:3
``````

### 僅在 Go `map` 中迭代值

``````package main

import "fmt"

func main() {
map_1 := map[int]string{
0: "Alok",
1: "Reman",
2: "Riken",
3: "Rudra",
}

for _, v := range map_1 {
fmt.Printf("Value:%s\n", v)
}
}
``````

``````Value:Riken
Value:Rudra
Value:Alok
Value:Reman
``````

Suraj Joshi is a backend software engineer at Matrice.ai.