【小记】go如何判断key是否在map中

go如何判断key是否在map中

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

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

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

查询方式如下,推荐使用check02的方式,因为check02在if里先运行表达式进行判断,更为简便

package main

import "fmt"

var(
	dict = map[string]int{"key1":1, "key2":2}
)

func check01(key string) {
	value, ok := dict[key]
	if ok {
		fmt.Println(value)
	}else {
		fmt.Println(key + " is not exist!")
	}
}


//简化写法
func check02(key string) {
	if value, ok := dict[key]; ok {
		fmt.Println(value)
	}else {
		fmt.Println(key + " is not exist!")
	}
}

func main() {
	check01("key1")
	check02("key3")
}
原文地址:https://www.cnblogs.com/kylinxxx/p/15414314.html