在 Go 中如何检查一个映射是否包含某个键?
我知道我可以使用
for k, v := range m { ... }
迭代映射
m
并查找键,但有没有更有效的方法来测试映射中键的存在?
以下是检查映射是否包含键的方法。
val, ok := myMap["foo"]
// If the key exists
if ok {
// Do something
}
这将初始化两个变量。如果映射中存在“foo”,则
val
是其值;如果不存在(在本例中为空字符串),则为“零值”。如果键存在,则
ok
是一个
bool
,它将设置为
true
。
如果您愿意,可以将其缩短为一行。
if val, ok := myMap["foo"]; ok {
//do something here
}
Go 允许您在 if 语句中的条件(注意分号)之前放置一个初始化语句。这样做的结果是
val
和
ok
的范围将限于 if 语句的主体,如果您只需要在那里访问它们,这将很有帮助。
除了 Go 编程语言规范 ,您还应该阅读 Effective Go 。在 maps 部分,他们说,除其他外:
An attempt to fetch a map value with a key that is not present in the map will return the zero value for the type of the entries in the map. For instance, if the map contains integers, looking up a non-existent key will return 0. A set can be implemented as a map with value type bool. Set the map entry to true to put the value in the set, and then test it by simple indexing.
attended := map[string]bool{ "Ann": true, "Joe": true, ... } if attended[person] { // will be false if person is not in the map fmt.Println(person, "was at the meeting") }
Sometimes you need to distinguish a missing entry from a zero value. Is there an entry for "UTC" or is that 0 because it's not in the map at all? You can discriminate with a form of multiple assignment.
var seconds int var ok bool seconds, ok = timeZone[tz]
For obvious reasons this is called the “comma ok” idiom. In this example, if tz is present, seconds will be set appropriately and ok will be true; if not, seconds will be set to zero and ok will be false. Here's a function that puts it together with a nice error report:
func offset(tz string) int { if seconds, ok := timeZone[tz]; ok { return seconds } log.Println("unknown time zone:", tz) return 0 }
To test for presence in the map without worrying about the actual value, you can use the blank identifier (_) in place of the usual variable for the value.
_, present := timeZone[tz]
在 go-nuts 电子邮件列表 中搜索,并找到了 Peter Froehlich 于 2009 年 11 月 15 日发布的解决方案。
package main
import "fmt"
func main() {
dict := map[string]int {"foo" : 1, "bar" : 2}
value, ok := dict["baz"]
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
或者,更简洁地说,
if value, ok := dict["baz"]; ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
请注意,使用这种形式的
if
语句,
value
和
ok
变量仅在
if
条件内可见。