Table of Contents
Different methods to check if key exists in map
We have already covered golang map in detail with multiple examples so in this tutorial we will stick to the main agenda. We will explore following methods to check if key exists in map in golang.
- Iterate over map elements and look out for the key
- Using index expression
- Perform a lookup for the key inside all the map elements
Method 1: iterate over a map
We can iterate over a map to check if the given key is in the map. The complexity of this method is O(n). We will break the loop once the key is found.
package main
import "fmt"
func main() {
var students = map[string]int{"April": 10, "Bob": 7,
"Caitlyn": 4, "Dean": 8, "Kelly": 6}
check := false
key := "Lynn"
anotherKey := "Dean"
ontherCheck := false
for k, _ := range students {
if key == k {
check = true
break
}
}
//iterate over the map
for k, _ := range students {
//if key in map => return true and break the loop
if anotherKey == k {
ontherCheck = true
break
}
}
if check {
fmt.Println("Lynn is in the map")
} else {
fmt.Println("Lynn is not in the map")
}
if ontherCheck {
fmt.Println("Dean is in the map")
} else {
fmt.Println("Dean is not in the map")
}
}
Output:
$ go run main.go
Lynn is not in the map
Dean is in the map
Method 2: Using  index expression
index expression
: A primary expression of the form a[x] denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively.
Addition to The Go Programming Language Specification and Effective Go, in the section on maps, they say, amongst other things:
An attempt to fetch a map value with a key that is not present in the map will return the zero value for the type of the entries in the map. For instance, if the map contains integers, looking up a non-existent key will return 0. A set can be implemented as a map with value type bool. Set the map entry to true to put the value in the set, and then test it by simple indexing.
Here is the example of how using index expression
to check a key is present in the map or not
package main
import "fmt"
func main() {
var students = map[string]int{"April": 10, "Bob": 7,
"Caitlyn": 4, "Dean": 8, "Kelly": 6}
//if key in map => ok is true
_, ok := students["Lynn"]
if ok {
fmt.Println("Lynn is in the map")
} else {
fmt.Println("Lynn is not in the map")
}
_, ok2 := students["Dean"]
if ok2 {
fmt.Println("Dean is in the map")
} else {
fmt.Println("Dean is not in the map")
}
}
Output:
$ go run main.go
Lynn is not in the map
Dean is in the map
Method-3: Perform a lookup in the map to check if key exists
We will just perform a lookup of all the elements inside the map and check if our key exists. Here is a sample code:
package main
import "fmt"
func main() {
var Employee = map[string]int{
"Deepak": 15000,
"Amit": 20000,
"Rahul": 30000,
"Ranjit": 40000,
}
keysToTest := []string{"Deepak", "Amit", "Trivedi"}
for _, emp := range keysToTest {
if _, exists := Employee[emp]; exists {
fmt.Printf("Key %s exists in map and has the value %v.\n", emp, Employee[emp])
} else {
fmt.Printf("Key %s does not exist in map.\n", emp)
}
}
}
Any attempt to fetch a map value with a key which is not present inside the go map will return the zero value for the respective type of the entries in the map. For instan0ce, if the map contains integers, looking up a non-existent key will return 0.
Sometimes you need to distinguish a missing entry from a zero value. Here we are using "comma ok idiom" to check if our emp
is present inside the Employee
map, value will be set appropriately and ok will be true
; if not, value will be set to zero and ok will be false
.
Output:
$ go run main.go Key Deepak exists in map and has the value 15000. Key Amit exists in map and has the value 20000. Key Trivedi does not exist in map.
Summary
In this Golang Tutorial, we learned how to check if specific key is present in a map, with the help of example programs. The complexity of using index pression is O(1) while the complexity of iterating over the entire map is O(n).
References
https://go.dev/ref/spec#Index_expressions
https://go.dev/doc/effective_go#maps
How to check if a map contains a key in Go?