go如何判斷key是否在map中
判斷key是否存在, 判斷方式為value,ok := map[key], ok為true則存在
if _, ok := map[key], ok {
//此為存在
}
if _, ok := map[key], !ok {
//此為不存在
}
查詢方式如下,推薦使用check02的方式,因為check02在if里先運行表達式進行判斷,更為簡便
package main
import "fmt"
var(
dict = map[string]int{"key1":1, "key2":2}
)
func check01(key string) {
value, ok := dict[key]
if ok {
fmt.Println(value)
}else {
fmt.Println(key + " is not exist!")
}
}
//簡化寫法
func check02(key string) {
if value, ok := dict[key]; ok {
fmt.Println(value)
}else {
fmt.Println(key + " is not exist!")
}
}
func main() {
check01("key1")
check02("key3")
}
