我是靠谱客的博主 酷炫彩虹,这篇文章主要介绍map 怎么确定 key 是否存在,如果访问了不存在的 key 会出现什么问题?,现在分享给大家,希望可以做个参考。

直接根据key去访问的话 ,返回的是值

访问了不存在的key会返回空 

如果判断的key值正好为bool 的 false值 ,则判断失误

所以要判断key值是否存在,可以用   value,key := map[key],   key为true则存在

package main

import "fmt"

func main()  {
	// map 判断key值是否存在 判断方式为value,key := map[key], key为true则存在
	demo := map[string] string{
		"name" : "tom",
		"phone" : "010-xxxx",
	}

	demo2 := map[string] bool{
		"hot" : true,
		"top" : false,
	}

	fmt.Println("demo1["name"]: ", demo["name"]) //tom
	fmt.Println("demo1["sex"]: ",demo["sex"]) //无输出

	fmt.Println("demo2["hot"]: ", demo2["hot"]) //true
	fmt.Println("demo2["top"]: ",demo2["top"]) //false  判断方式错误 top存在 但是返回值为false

	_, name := demo["name"]
	fmt.Println("is exist demo1["name"] ?",name) //true

	_, sex := demo["sex"]
	fmt.Println("is exist demo1["sex"] ?",sex) //false

	if _, hot := demo2["hot"]; hot{
		fmt.Println("is exist demo2["hot"] ?",hot) //true
	}


	if _, top := demo2["hot"]; top{
		fmt.Println("is exist demo2["top"] ?",top)//true
	}

	if _, old := demo2["old"]; old{
		fmt.Println("is exist demo2["old"] ?",old)
	}else {
		fmt.Println("is exist demo2["old"] ?",old) //false
	}
}

 

 

 

 

最后

以上就是酷炫彩虹最近收集整理的关于map 怎么确定 key 是否存在,如果访问了不存在的 key 会出现什么问题?的全部内容,更多相关map内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部