【小记】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")
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM