问题
I know I can iterate over a map m
by,
for k, v := range m { ... }
and look for a key but is there a more efficient way of testing a key’s existence in a map?
答案
package main
import "fmt"
func main() {
dict := map[string]int {"foo" : 1, "bar" : 2}
value, ok := dict["foo"]
if ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
}
Or, more compactly,
if value, ok := dict["foo"]; ok {
fmt.Println("value: ", value)
} else {
fmt.Println("key not found")
}
Note, using this form of the if
statement, the value
and ok
variables are only visible inside the if
conditions.
解释
if
statements in Go can include both a condition and an initialization statement. The example above uses both:
- initializes two variables -
val
will receive either the value of “foo” from the map or a “zero value” (in this case the empty string) andok
will receive a bool that will be set totrue
if “foo” was actually present in the map - evaluates
ok
, which will betrue
if “foo” was in the map
If “foo” is indeed present in the map, the body of the if
statement will be executed and val
will be local to that scope.
参考
https://stackoverflow.com/questions/2050391/how-to-check-if-a-map-contains-a-key-in-go