How to Check If a Map Contains a Key in Golang

To check if a map contains a key in Golang, you can use the form of the index expression v, ok := mainMap[“k”], which returns two elements: a value v of the map with the key k and a boolean value ok equal to true if the key k is present in the map. And then use the if statement to do something based on the value of ok.

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.

Leave a Comment