英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论