问题

I know I can iterate over a map m by,

  1. 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?

答案

  1. package main
  2. import "fmt"
  3. func main() {
  4. dict := map[string]int {"foo" : 1, "bar" : 2}
  5. value, ok := dict["foo"]
  6. if ok {
  7. fmt.Println("value: ", value)
  8. } else {
  9. fmt.Println("key not found")
  10. }
  11. }

Or, more compactly,

  1. if value, ok := dict["foo"]; ok {
  2. fmt.Println("value: ", value)
  3. } else {
  4. fmt.Println("key not found")
  5. }

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) and ok will receive a bool that will be set to true if “foo” was actually present in the map
  • evaluates ok, which will be true 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