根据 map 上的 Golang 文档,
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
所以我要确定给定字符串是否存在一个结构,我该如何确定呢?我会检查一个带有零值的空结构吗?这里的比较会是什么样子?
type Hello struct{}
structMap := map[string]Hello{}
j := structMap["example"]
if(j==?) {
...
}
最佳答案
使用特殊的“comma, ok”形式来告知是否在 map 中找到了键。去Spec: Index Expressions:
An index expression on a map
a
of typemap[K]V
used in an assignment or initialization of the special formv, ok = a[x] v, ok := a[x] var v, ok = a[x]
yields an additional untyped boolean value. The value of
ok
istrue
if the keyx
is present in the map, andfalse
otherwise.
所以在你的代码中:
type Hello struct{}
structMap := map[string]Hello{}
if j, ok := structMap["example"]; !ok {
// "example" is not in the map
}
关于dictionary - 检测映射中的键是否存在结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30213739/