[Go] Check whether a map contains a key

Created on November 30, 2026

The two-result map lookup, value, ok := m[key], reports whether the key exists. Use _ for the value if you only need to test for the key.

package main

import "fmt"

func main() {
    messages := map[string]string{
        "a": "hello",
        "b": "world",
    }
    _, ok := messages["a"]
    fmt.Println(ok)
}
true

An existing key can have the zero value for its element type. The ok result still reports that it is present.

Go