How to Check Whether a Map Contains a Key in Go
Go has a built-in idiom for checking whether a map contains a key. A map lookup can return both the stored value and a boolean indicating whether the key is present.
Check a Key
myMap := map[string]int{
"apple": 1,
"banana": 2,
"cherry": 3,
}
key := "banana"
value, exists := myMap[key]
if exists {
fmt.Printf("Key '%s' exists with value %d\n", key, value)
} else {
fmt.Printf("Key '%s' does not exist\n", key)
}The boolean is important because a missing key returns the value type’s zero value. Without the boolean, you cannot distinguish a missing key from a present key whose stored value happens to be zero.
Check Only for Presence
If you do not need the value, discard it with _:
key := "grape"
_, exists := myMap[key]
if !exists {
fmt.Printf("Key '%s' does not exist\n", key)
}A compact form is also common:
if value, ok := myMap[key]; ok {
fmt.Println(value)
}Custom Key Types
Map keys may use any comparable type, including structs whose fields are all comparable:
type Person struct {
Name string
Age int
}
myMap := map[Person]string{
{Name: "Alice", Age: 30}: "Engineer",
{Name: "Bob", Age: 25}: "Artist",
}
person := Person{Name: "Alice", Age: 30}
value, exists := myMap[person]
if exists {
fmt.Printf("Person '%v' exists with value '%s'\n", person, value)
}The lookup pattern is exactly the same regardless of key type.
Conclusion
Use value, ok := m[key] whenever you need to know whether a key is actually present in a Go map. It is concise, avoids ambiguity around zero values, and is the standard Go idiom for map membership checks.