在地图中检测键是否存在结构体。

huangapple go评论87阅读模式
英文:

Detecting if struct exists for key in map

问题

根据Golang关于映射的文档,

如果请求的键不存在,我们会得到值类型的零值。在这种情况下,值类型是int,所以零值是0:

j := m["root"] // j == 0

所以我想确定是否存在一个给定字符串的结构体,我该如何确定?我只需要检查一个具有零值的空结构体吗?这里的比较应该是什么样的?

type Hello struct{}
structMap := map[string]Hello{}
j := structMap["example"]
if(j==?) {
 ...
}
英文:

According to the Golang documentation on maps,

> If the requested key doesn't exist, we get the value type's zero value. In this case the value type is int, so the zero value is 0:
>
> j := m["root"] // j == 0

So I'm trying to determine if a struct exists with a given string, how would I determine this? Would I just check for an empty struct with zerod values? What would the comparison here look like?

type Hello struct{}
structMap := map[string]Hello{}
j := structMap["example"]
if(j==?) {
 ...
}

答案1

得分: 11

使用特殊的"逗号, ok"形式来判断键是否存在于映射中。参考规范:索引表达式

在赋值或初始化的特殊形式中,对类型为map[K]V的映射a进行索引表达式

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]

会产生一个额外的无类型布尔值。如果键x存在于映射中,ok的值为true,否则为false

因此,在你的代码中:

type Hello struct{}
structMap := map[string]Hello{}
if j, ok := structMap["example"]; !ok {
    // "example"不在映射中
}
英文:

Use the special "comma, ok" form which tells if the key was found in the map. Go Spec: Index Expressions:

> An index expression on a map a of type map[K]V used in an assignment or initialization of the special form
>
> v, ok = a[x]
> v, ok := a[x]
> var v, ok = a[x]
>
> yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

So in your code:

type Hello struct{}
structMap := map[string]Hello{}
if j, ok := structMap["example"]; !ok {
    // "example" is not in the map
}

huangapple
  • 本文由 发表于 2015年5月13日 19:40:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/30213739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定