How to Check if a Key Exists in a Golang Map
It is often required to know whether a map has a key in it so that we don’t crash our app trying to access a key that does not exist. So how do we do it in golang?
Different programming languages do this in different ways. Python does this with exceptions. It raises an exception wen trying to read a key that is not in the dict. So how does golang do this?
As with everything else in golang, there is an easy way for this as well. You just have to write an if
condition as follows:
if val, ok := dict["foo"]; ok {
//do something here
}
if
statements in Go can include both a condition and an initialization statement.
Here, 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