tags:

views:

192

answers:

3

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? Thanks. I couldn't find an answer in the language spec.

+1  A: 

Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.

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")
        }
}

Or, more compactly,

if value, ok := dict["baz"]; 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.

grokus
If you really are just interested in whether the key exists or not, and don't care about the value, you can use `_, ok := dict["baz"]; ok`. The `_` part throws the value away instead of creating a temporary variable.
Matthew Crumley
+6  A: 

One line answer:

if val,ok := dict["foo"]; ok {
    //do something here
}
marketer
+5  A: 

In addition to The Go Programming Language Specification, you should read Effective Go. In the section on maps, they say, amongst other things:

"An attempt to fetch a map value with a key that is not present in the map will cause the program to crash, but there is a way to do so safely using a multiple assignment."

var seconds int
var ok bool
seconds, ok = timeZone[tz]

"To test for presence in the map without worrying about the actual value, you can use the blank identifier, a simple underscore (_). The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly. For testing presence in a map, use the blank identifier in place of the usual variable for the value."

_, present := timeZone[tz]
peterSO