How to Check If a Map Key Exists in Go
A map in Go is an unordered collection of data that may contain one or more properties, each with a key and value. The strength of a map is its ability to retrieve data quickly based on a key. However, when you try to access the value of a map key that does not exist, you’ll get the zero value for the type of the values in the map. This does not help distinguish between a key that exists in the map but is explicitly assigned to the zero value of the type and one that is nonexistent.
func main() {
m1 := map[string]int{
"a": 0,
"b": 1,
"c": 2,
}
// "a" exists in map
v1 := m1["a"]
fmt.Println(v1) // 0
// "f" does not exist in the map
v2 := m1["f"]
fmt.Println(v2) // 0
// How to distinguish between the two?
}
To solve this problem, you must use an index expression. Here’s how it works:
func main() {
m1 := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
if v, exists := m1["a"]; exists {
// The "a" key exists in map
fmt.Println(v) // 1
} else {
// if "a" does not exist
fmt.Println("Key not found")
} // `v` and `exists` go out of scope here
}
The v
and exists
variables are bound to the scope of the if
block
(including any else
or else if
blocks) so you cannot access them outside
this block. If you need to access either variable outside the if
block, you
must declare them outside as well:
func main() {
m1 := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
v, exists := m1["a"]
if exists {
// The "a" key exists in map
fmt.Println(v) // 1
} else {
// "a" does not exist
m1["a"] = 40
}
// `v` and `exists` remain accessible
}
The exists
variable will be true
if the specified key exists in the map,
otherwise, it will be false
. Some prefer to name the second variable ok
instead of exists
:
v, ok := m1["a"]
if ok {
fmt.Println(v)
}
If you only want to check if a key exists without caring about its actual
value, assign the value to the blank operator (_
).
_, ok := m1["a"]
if ok {
// do something
}
Thanks for reading, and happy coding!