How to Check If a Map Contains a Key in Golang

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

Copy a Map in Golang

Merge Maps in Golang