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?
I couldn't find the answer in the language spec.
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?
I couldn't find the answer in the language spec.
Edit: The following answer is prior to Go 1. Starting with Go 1, it is no longer accurate / valid.
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."
"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."
One line answer:
Explanation:
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 mapevaluates
ok
, which will betrue
if "foo" was in the mapIf "foo" is indeed present in the map, the body of the
if
statement will be executed andval
will be local to that scope.Just use
Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.
Or, more compactly,
Note, using this form of the
if
statement, thevalue
andok
variables are only visible inside theif
conditions.better way here
Short Answer
Example
Here's an example at the Go Playground.
Longer Answer
Per the Maps section of Effective Go: