Check if a Map Contains a Key in Go
Go is an exceptional programming language of the modern age. It comes packed with tons of features and performance benefits that are hard to achieve with languages with similar syntax and learning curve.
Go provides us with the map data type which is a built-in data type that associates values of one type (the key) with values of another type (the value). You are probably familiar with this data type under the name hash or dictionary.
When working with maps, you may encounter instances where you need to check whether a given key is located in the map.
In this tutorial, we will explore various methods and techniques we can use to determine whether a map contains a specific key.
Requirements
To follow along with this post, you should have:
- The Go compiler installed on your machine.
- Basic understanding of the Go programming language.
The comma-ok idiom
The most common method we can use to check whether a given exists in a map is the comma-ok feature in Go. It returns 0 if the specified key does not exist in the map.
To better understand how to use it, consider the example below:
package main
import "fmt"
func main() {
m := map[string]int{
"k1": 1,
"k2": 2,
"k3": 3,
}
keyToCheck := "k2"
if value, ok := m[keyToCheck]; ok {
fmt.Printf("Key %s exists with value %d\n", keyToCheck, value)
} else {
fmt.Printf("Key %s does not exist\n", keyToCheck)
}
}
The value, ok := m[keyToCheck]
statement will return two values. The first is the value associated with the key, and the second is a Boolean that will be true
if the key was present in the map, and false
if it was not.
The code above should return:
Key k2 exists with value 2
Accessing the Key
We can also verify the existence of a given key in a map by accessing it. One disadvantage of this technique is that it can be misleading. This is because Go will return the zero value of the value type if the key doesn’t exist. Hence, if there’s a zero value in the map, you may not know whether the result is for the value of the missing key.
An example is as shown:
package main
import "fmt"
func main() {
m := map[string]int{
"k1": 1,
"k2": 0,
"k3": 3,
}
keyToCheck := "k2"
value := m[keyToCheck]
fmt.Printf("Key %s has value %d\n", keyToCheck, value)
}
In the example, the key k2
exists in the map with a value of 0
. However, if k2
did not exist in the map, we would still get 0
as a result, leading to potential confusion.
Conclusion
In this tutorial, we discussed two main methods of checking whether a map contains a key in Go. We recommended sticking with the comma-Ok feature in Go as it provides a clear distinction on whether the key exists and not a zero value stored in the key.