dictionary - 检测映射中的键是否存在结构

标签 dictionary go

根据 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 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.

所以在你的代码中:

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/

相关文章:

java - 在 Kotlin 中映射的可变参数

python - 如何将词典列表输出到 Excel 工作表?

python - 如何将python dict与多处理同步

go - Travis 看到 GO 函数的旧签名并且不会构建

go - 了解不同系统上的tz偏移差异

python - 在 Golang 的 Tensorflow 中打开带有嵌入层的 Keras 模型

python 嵌套 dict 到 csv 有很多列

python - 解析和排序 Python 字典中的键

google-app-engine - 在 AppEngine 上使用 Go 连接到第二代 Google SQL Cloud

go - 即使初始化后变量也为零