如何检查地图是否包含 Go 中的键? [英] How to check if a map contains a key in Go?

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

问题描述

我知道我可以通过 m 遍历地图,

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?

我在语言规范中找不到答案.

推荐答案

一行回答:

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

说明:

Go 中的

if 语句可以包含条件语句和初始化语句.上面的例子同时使用了两者:

Explanation:

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

  • 初始化两个变量 - val 将从地图中接收foo"的值或零值"(在本例中为空字符串)和 ok 将收到一个布尔值,如果foo"实际上存在于地图中,则该布尔值将被设置为 true

  • 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",则将执行 if 语句的主体,并且 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.

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

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