检查地图中的元素
要从地图中获取值,你只需执行以下操作:00
value := mapName[ key ]
如果映射包含键,则返回相应的值。
如果不是,则返回地图值类型的零值(如果 int
值的地图则为 0
,如果是 string
值的地图则为 ""
…)
m := map[string]string{"foo": "foo_value", "bar": ""}
k := m["foo"] // returns "foo_value" since that is the value stored in the map
k2 := m["bar"] // returns "" since that is the value stored in the map
k3 := m["nop"] // returns "" since the key does not exist, and "" is the string type's zero value
要区分空值和不存在的键,可以使用映射访问的第二个返回值(使用类似 value, hasKey := map["key"]
)。
第二个值是 boolean
类型,将是:
true
当值在地图中时,false
当地图不包含给定的密钥时。
请看以下示例:
value, hasKey = m[ key ]
if hasKey {
// the map contains the given key, so we can safely use the value
// If value is zero-value, it's because the zero-value was pushed to the map
} else {
// The map does not have the given key
// the value will be the zero-value of the map's type
}