go语言如何判断 map 中是否包含某个 key
warning:
这篇文章距离上次修改已过453天,其中的内容可能已经有所变动。
在 Go 语言中,可以使用内建的 ok 机制来判断 map 中是否含有某个 key。这种方式在查找时不会引发 panic,而是返回一个布尔值。如果 key 存在,ok 会是 true,如果不存在,ok 会是 false。
以下是一些示例代码:
方法一:
m := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
_, ok := m["two"]
if ok {
fmt.Println("Map contains 'two' key")
} else {
fmt.Println("Map does not contain 'two' key")
}方法二:
m := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
_, exists := m["two"]
if exists {
fmt.Println("Map contains 'two' key")
} else {
fmt.Println("Map does not contain 'two' key")
}在这两个示例中,我们都是在 map m 中查找 key "two"。如果 key 存在,我们就打印出 "Map contains 'two' key",如果不存在,我们就打印出 "Map does not contain 'two' key"。
注意:在 Go 语言中,map 的 key 是否存在,是不能直接通过判断其是否为 nil 来判断的。因为 nil map 和 空 map 在 Go 语言中是有区别的。nil map 不能使用,尝试使用会引发 panic,而空 map 可以使用,但是没有任何数据。所以,判断 map 中是否包含某个 key,应该使用 ok 机制。
评论已关闭