golang map 判断是否包含某个key
在Go语言中,可以使用_, ok := map[key]的方式来判断一个map是否包含某个key。如果map中包含该key,则ok的值为true,否则为false。下面是一个示例代码:
package main
import "fmt"
func main() {
m := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
key := "b"
_, ok := m[key]
if ok {
fmt.Printf("map contains key '%s'\n", key)
} else {
fmt.Printf("map does not contain key '%s'\n", key)
}
}
输出结果为:
map contains key 'b'
如果要判断一个map是否不包含某个key,可以直接使用if !ok的方式。
原文地址: http://www.cveoy.top/t/topic/hLFB 著作权归作者所有。请勿转载和采集!