Go 语言中如何判断 map 中是否存在某个键
在 Go 语言中没有直接的 'containsKey' 方法,但是可以通过使用 'map' 类型的 '_, ok := myMap[key]' 语法来检查一个键是否存在于 'map' 中。如果 'ok' 的值为 'true',表示键存在于 'map' 中,否则表示键不存在。
示例代码如下:
myMap := map[string]int{
'key1': 1,
'key2': 2,
}
if _, ok := myMap['key1']; ok {
fmt.Println('Key exists')
} else {
fmt.Println('Key does not exist')
}
如果 'myMap' 中存在键 'key1',则会输出 'Key exists',否则输出 'Key does not exist'。
原文地址: https://www.cveoy.top/t/topic/qAj0 著作权归作者所有。请勿转载和采集!