Home » How to Check If Key Exists in Map in Golang

How to Check If Key Exists in Map in Golang

Golang stores the data values in key-value pairs. To check if the key exists in the map in Go, access the key using the expression map[key]. It returns the boolean value true or false if the key exists or not.

Use the if statement to check whether the condition of the key exists or not.

In this article, we will discuss how to check if a key exists in the golang map.

How to Check if a Key Exists in Golang Map

We can access the element in a golang map using its key. if the key is not present, it will return the value type zero value.

To check if a key exists in the golang map, refer to the below code.

package main

import (
	"fmt"
)

func main() {

	// Create a map in go using the make function

	score := make(map[string]int)

	// Add elements to map
	score["Alex"] = 94
	score["Gary"] = 75
	score["Mary"] = 67

	// Example-1
        // Use if statement to check if a key exists in a map in golang
	// Check for key "Gary" in if statement,
	// if key exists, print the value for a given key

	if _, found := score["Sam"]; found {
		fmt.Println("Key exists in map, its value: ", score["Sam"])
	} else {
		fmt.Print("Key doesn't exists in a map")
	}

	fmt.Printf("\n")
	
	// Example-2 
        //Other simple way to check key is present or not
	// access the key to get its value, if the key is not present in map, it will return false in found

	value, found := score["Mary"]
	if found {
		fmt.Println("Key is available in map, value is: ", value)
	} else {
		fmt.Println("Key is not available in map,value is: ", value)
	}
}

The output of the above Golang program to check if a key exists in a map is:

Key doesn't exists in a map

Key is available in map, value is:  67

Example-1, uses the if statement to check if a key exists in the map condition in the if statement itself, and if true or false, it prints the message.

In Example-2, the value,found:= score[“Mary”] expression stores the result, like value for the given key, and the found variable stores either true or false value. In the if statement, it checks for the found variable value and prints the message.

Conclusion

I hope the above article on how to check if a key exists in a map in golang is helpful to you.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Leave a Comment