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
	}
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值