The easiest way to “check if a key exists in a map is to use the comma-ok operator.” The “comma-ok” operator returns two values: the value of the key if it exists or the zero value for the type of the key if it does not exist.
Syntax
v, ok := mainMap["k"]
if ok {
// Do something
}
Example
package main
import (
"fmt"
)
func main() {
a := map[string]int{"one": 1, "two": 2}
v, ok := a["one"]
if ok {
fmt.Println(v)
fmt.Println("The map contains a key")
}
v, ok = a["three"]
if !ok {
fmt.Println(v)
fmt.Println("The map does not contain a key")
}
}
Output
1
The map contains a key
0
The map does not contain a key
The v variable will contain the value associated with the key if it exists in the map. If the key does not exist in the map, the v variable will be set to the zero value of the map’s value type (e.g., 0 for an int value).
The ok variable will be a bool that indicates whether the key exists in the map. If ok is true, the key exists in the map; if ok is false, the key does not exist.
That’s it!
Related posts
How to Delete a Key from a Map in Golang

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.