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.
It is mentioned under "Index expressions".
As noted by other answers, the general solution is to use an index expression in an assignment of the special form:
This is nice and clean. It has some restrictions though: it must be an assignment of special form. Right-hand side expression must be the map index expression only, and the left-hand expression list must contain exactly 2 operands, first to which the value type is assignable, and a second to which a
bool
value is assignable. The first value of the result of this special form index expression will be the value associated with the key, and the second value will tell if there is actually an entry in the map with the given key (if the key exists in the map). The left-hand side expression list may also contain the blank identifier if one of the results is not needed.It's important to know that if the indexed map value is
nil
or does not contain the key, the index expression evaluates to the zero value of the value type of the map. So for example:Try it on the Go Playground.
So if we know that we don't use the zero value in our map, we can take advantage of this.
For example if the value type is
string
, and we know we never store entries in the map where the value is the empty string (zero value for thestring
type), we can also test if the key is in the map by comparing the non-special form of the (result of the) index expression to the zero value:Output (try it on the Go Playground):
In practice there are many cases when we don't store the zero-value value in the map, so this can be used quite often. For example interfaces and function types have a zero value
nil
, which we often don't store in maps. So testing if a key is in the map can be achieved by comparing it tonil
.Using this "technique" has another advantage too: you can check existence of multiple keys in a compact way (you can't do that with the special "comma ok" form). More about this: Check if key exists in multiple maps in one condition
Then, go run maps.go somestring exists? true not exists? false
A two value assignment can be used for this purpose. Please check my sample program below