I know I can iterate over a map m
with
for k, v := range m { ... }
and look for a key, but is there a more efficient way of testing for a key's existence in a map?
Here's how you check if a map contains a key.
val, ok := myMap["foo"]
// If the key exists
if ok {
// Do something
}
This initializes two variables. val
is the value of "foo" from the map if it exists, or a "zero value" if it doesn't (in this case the empty string). ok
is a bool
that will be set to true
if the key existed.
If you want, you can shorten this to a one-liner.
if val, ok := myMap["foo"]; ok {
//do something here
}
Go allows you to put an initializing statement before the condition (notice the semicolon) in the if statement. The consequence of this is that the scope ofval
and ok
will be limited to the body of the if statement, which is helpful if you only need to access them there.