How to check if a key exists in a map in Golang?


We know that maps in Go contain key-value pairs. There are often instances where we would want to know that a certain key exists in a map or not, in such cases, we have two options available.

  • The first approach is very naive, as in this approach, we basically iterate over the map with the help of the range clause and then compare each key to the key that we want to check if is available or not.

  • And the second approach is a bit better, as we make use of the if statement with a bit of syntactic sugar.

Let's first check the naive approach in action.

Example 1

Consider the code shown below.

package main
import (
   "fmt"
)
func main() {
   m := make(map[string]int)
   m["mukul"] = 10
   m["mayank"] = 9
   m["deepak"] = 8
   for key := range m {
      if key == "naina" {
         fmt.Println("Key named naina exists in the map")
      }
   }
   fmt.Println("No key named naina is present in the map")
   fmt.Println(m)
}

In the above code,

  • We have declared a map named m which contains the keys that are of string data type and values that are of integer data type.

  • Then we are using the range clause in a for loop to iterate over all the keys that are present in the map, and inside that loop, we are iterating over the keys and then comparing each key with the key that we want to check.

The above approach is not recommended, as the size of the map can be much bigger, which in turn will increase the time complexity of the solution.

Output

If we run the above code with the command go run main.go, then we will get the following output in the terminal.

No key named naina is present in the map
map[deepak:8 mukul:10 mayank:9]

A much better approach is to use the if syntax to check if a particular value exists in the map or not.

Example 2

Consider the code shown below.

package main
import (
   "fmt"
)
func main() {
   m := make(map[string]int)
   m["mukul"] = 10
   m["mayank"] = 9
   m["deepak"] = 8
   fmt.Println(m)
   if _, ok := m["naina"]; ok {
      fmt.Println("The key exists in the map")
   } else {
      fmt.Println("No key named naina in the map")
   }
}

In the above code,

  • We just use the if condition and then check the value, just like we get a value from an array.

  • But instead of passing the index, we pass the key, and the result will then be stored in the variable called ok.

  • Then we append the ok condition along with it, and if the key exists, then we will get the result, else we will get "it doesn't exist".

Output

If we run the above code with the command go run main.go, then we will get the following output in the terminal.

map[mukul:10 mayank:9 deepak:8]
No key named naina in the map

Updated on: 21-Feb-2022

690 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements