Go Map 中判断 Key 是否存在
在 Golang 中,可以使用 _, ok := map[key] 的方式来判断一个键是否存在于 Map 中。如果 ok 为 true,则表示键存在于 Map 中;如果 ok 为 false,则表示键不存在于 Map 中。
以下是一个示例代码:
package main
import "fmt"
func main() {
myMap := map[string]int{
'a': 1,
'b': 2,
'c': 3,
}
key := 'b'
value, ok := myMap[key]
if ok {
fmt.Printf('键 %s 存在,对应的值为 %d\n', key, value)
} else {
fmt.Printf('键 %s 不存在\n', key)
}
}
输出结果为:
键 b 存在,对应的值为 2
原文地址: https://www.cveoy.top/t/topic/bcPp 著作权归作者所有。请勿转载和采集!