检测地图中的键是否存在struct

All*_*len 0 dictionary go

根据地图上的Golang文档,

如果请求的密钥不存在,我们将获得值类型的零值.在这种情况下,值类型为int,因此零值为0:

j := m["root"] // j == 0
Run Code Online (Sandbox Code Playgroud)

所以我试图确定一个结构是否存在一个给定的字符串,我该如何确定?我会检查一个带有零值的空结构吗?这里的比较会是什么样的?

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

icz*_*cza 7

使用特殊的"逗号,确定"形式,告诉您是否在地图中找到了密钥.Go Spec:索引表达式:

在特殊表单的赋值或初始化中使用a的类型映射上的索引表达式map[K]V

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]
Run Code Online (Sandbox Code Playgroud)

产生一个额外的无类型布尔值.的值oktrue如果该键x存在于地图,和false其它.

所以在你的代码中:

type Hello struct{}
structMap := map[string]Hello{}
if j, ok := structMap["example"]; !ok {
    // "example" is not in the map
}
Run Code Online (Sandbox Code Playgroud)