🗝️ Check if a map contains a key in Go
Table of Contents
To check if a given key exists in a map in Go, use the special form of the index expression v, ok := a[k] which returns two elements - a value v of the map with the key k, and a boolean value ok equal to true if the key k is present in the map. If not, the ok is false.
Example #
data := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
val, ok := data["a"]
fmt.Println(val, ok)
val, ok = data["d"]
fmt.Println(val, ok)
Output:
1 true
0 false
How to check if a key exists in a map directly in an if statement #
In everyday coding, a common situation is that you only want to execute a certain piece of code if a given key exists in the map. In Go, you can do this by combining the if statement with the map index expression.
if val, ok := data["a"]; ok {
fmt.Println(val, ok)
}
if val, ok := data["d"]; ok {
fmt.Println(val, ok)
}
Output:
1 true
If statements can be preceded by simple statements that allow you to assign map values directly in the if, before evaluating it.
Why is checking for zero values not sufficient? #
You may be wondering why we cannot use the simpler map index expression which returns a single value and check if it is not the zero value:
if data["a"] != 0 {
fmt.Println("key a exists")
}
Output:
key a exists
It works fine if you are sure that your map does not contain zero values. Otherwise, the result will be incorrect:
// incorrect result
data["d"] = 0
if data["d"] != 0 {
fmt.Println("key d exists")
} else {
fmt.Println("key d does not exist")
}
Output:
key d does not exist
For this reason, it is a better idea to use a two-values map index expression for checking whether a map contains a given key in Go.