如何检查地图是否包含一个钥匙去? [英] How to check if a map contains a key in go?

查看:116
本文介绍了如何检查地图是否包含一个钥匙去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以迭代一个地图,通过

I know I can iterate over a map m by,

for k, v := range m { ... }

并寻找一个关键字,但是是否有更有效的方式来测试一个关键字在地图中的存在?谢谢。我在语言规范中找不到答案。

and look for a key but is there a more efficient way of testing a key's existence in a map? Thanks. I couldn't find an answer in the language spec.

推荐答案

一行答案:

if val, ok := dict["foo"]; ok {
    //do something here
}



说明:



如果Go中的语句可以包含条件和初始化语句。上面的例子同时使用:

Explanation:

if statements in Go can include both a condition and an initialization statement. The example above uses both:


  • 初始化两个变量 - val 从地图或零值(在这种情况下为空字符串)和 ok 将收到一个将被设置为 code> true 如果foo实际存在于地图中

  • initializes two variables - val will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok will receive a bool that will be set to true if "foo" was actually present in the map

评估 ok ,如果地图中有foo,则 true $ / $>

evaluates ok, which will be true if "foo" was in the map

如果地图中确实存在foo,则如果语句的正文将被执行,并且 val 将是该范围的本地。

If "foo" is indeed present in the map, the body of the if statement will be executed and val will be local to that scope.

这篇关于如何检查地图是否包含一个钥匙去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆