Check if Key is Present in Map

To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.

In this tutorial, we will learn how to check if key is present in Map.

Syntax

The syntax to get the logical value if key is present in Map x is

_, isPresent := x[key]

If key is present, then isPresent is true.

If key is not present, then isPresent is false.

ADVERTISEMENT

Examples

Key present in Map

In the following program, we take a map map1 and check if key "b" is present in this map. The key "b" is present in given map, therefore, isPresent must be assigned with true.

example.go

package main

import "fmt"

func main() {
	map1 := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	_, isPresent := map1["b"]

	if isPresent {
		fmt.Print("The key is present in map.")
	} else {
		fmt.Print("The key is not present in map.")
	}
}

Output

The key is present in map.

Now, let us check for a key "c" that is not present in the map map1. Since, given key is not present in the map, isPresent must be assigned with false.

example.go

package main

import "fmt"

func main() {
	map1 := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	_, isPresent := map1["m"]

	if isPresent {
		fmt.Print("The key is present in map.")
	} else {
		fmt.Print("The key is not present in map.")
	}
}

Output

The key is not present in map.

Conclusion

In this Golang Tutorial, we learned how to check if specific key is present in a Map, with the help of example programs.