golang map 判断key是否存在

  • Post author:
  • Post category:golang


判断方法示例代码

if _, ok := map[key]; ok {
    // 存在
}

if _, ok := map[key]; !ok {
    // 不存在
}

判断方式为value,ok := map[key], ok为true则存在

示例:

package main
 
import "fmt"
 
func main() {
    demo := map[string]bool{
        "a": false,
    }
 
    //错误,a存在,但是返回false
    fmt.Println(demo["a"])
 
    //正确判断方法
    _, ok := demo["a"]
    fmt.Println(ok)
}

输出:

false
true