0
0
GoHow-ToBeginner · 3 min read

How to Check if Key Exists in Map in Go

In Go, you check if a key exists in a map by using the syntax value, ok := map[key]. The ok variable is a boolean that is true if the key exists and false if it does not.
📐

Syntax

To check if a key exists in a map, use the two-value assignment form:

  • value: the value stored at the key (zero value if key missing)
  • ok: a boolean that is true if the key exists, false otherwise
go
value, ok := myMap[key]
💻

Example

This example shows how to check if a key exists in a map and handle both cases.

go
package main

import "fmt"

func main() {
    ages := map[string]int{"Alice": 25, "Bob": 30}

    age, ok := ages["Alice"]
    if ok {
        fmt.Printf("Alice's age is %d\n", age)
    } else {
        fmt.Println("Alice not found")
    }

    age, ok = ages["Eve"]
    if ok {
        fmt.Printf("Eve's age is %d\n", age)
    } else {
        fmt.Println("Eve not found")
    }
}
Output
Alice's age is 25 Eve not found
⚠️

Common Pitfalls

A common mistake is to check the value directly without the ok boolean, which can cause confusion if the value's zero value is valid.

For example, if the map stores integers, a missing key returns 0, which might be mistaken as a valid value.

go
package main

import "fmt"

func main() {
    scores := map[string]int{"John": 0}

    // Wrong way: checking value only
    if scores["John"] != 0 {
        fmt.Println("John has a score")
    } else {
        fmt.Println("John has no score or key missing")
    }

    // Right way: check with ok
    score, ok := scores["John"]
    if ok {
        fmt.Printf("John's score is %d\n", score)
    } else {
        fmt.Println("John not found")
    }
}
Output
John has no score or key missing John's score is 0
📊

Quick Reference

Remember these tips when checking keys in Go maps:

  • Use value, ok := map[key] to safely check existence.
  • Do not rely on the value alone if zero values are possible.
  • ok is true only if the key exists.

Key Takeaways

Use the two-value assignment value, ok := map[key] to check if a key exists.
ok is a boolean that tells if the key is present in the map.
Never rely on the value alone to check existence if zero values are valid.
Always handle both cases: key found and key not found.
This method works for all map types in Go.