# 如何在 Go 中检查 map 中是否包含某个键

Suraj Joshi 2023年1月30日

## Go 中 `map` 数据结构

### map 的语法

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

``````package main

import "fmt"

func main() {
map_1 := map[string]string{
"Jenna": "Sthapit",
}

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

}
``````

``````Key:Jenna
Value: Sthapit
``````

## 在 Go `map` 中检查键值

### Go map 中检查是否包含某键

``````first_value, second_value := map_name[key_name]
``````

``````package main

import "fmt"

func main() {
map_name := map[int]string{
0: "Alok",
1: "Reman",
2: "Riken",
3: "Rudra",
}
_, second_value_1 := map_name[1]
fmt.Printf("second_value for 1: %t\n", second_value_1)

_, second_value_9 := map_name[9]
fmt.Printf("second_value for 9: %t\n", second_value_9)
}
``````

``````second_value for 1: true
second_value for 9: false
``````

``````package main

import "fmt"

func main() {
map_name := map[string]string{
"Giri":     "Alok",
"Nembang":  "Reman",
"Maharjan": "Riken",
"Jha":      "Rudra",
}
if first_value, second_value := map_name["Giri"]; second_value {
fmt.Printf("Giri is present in map. Value is: %s\n", first_value)
} else {
fmt.Printf("Giri is not present in map.\n")
}

if first_value, second_value := map_name["Sthapit"]; second_value {
fmt.Printf("Sthapit is present in map. Value is: %s\n", first_value)
} else {
fmt.Printf("Sthapit is not present in map. \n")
}
}

``````

``````Giri is present in map. Value is: Alok
Sthapit is not present in map.
``````

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