How To Check If A Map Contains A Key In Go?

How to check if a map contains a key in Go?

Go (Golang) Maps are a powerful data structure that allow you to store key-value pairs. They are often used to store data that is accessed frequently, such as user information or product inventory. The values are accessed easily without having to iterate through all elements, like you would do for examples with slices (arrays).

One of the most common tasks when working with maps is to check if a key exists. This can be done in a few different ways. You don't need to install any third party packages if you want to check the existence of a key in a map in Go. Everything can be done using the standard library

Using the comma, ok syntax

The most common way to check if a key exists in a map is to use the comma-ok operator. This 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.

Here's how it works, the following code checks if the key exists in the map users:

package main

import "fmt"

func main() {
  users := map[string]string{
    "bob": "New York",
    "lisa": "Japan",
    "marco": "Italy",
  city, ok := users["bob"]
  if ok {
    fmt.Println("bob lives in", city)
  } else {
    fmt.Println("bob is not in the map")
  city, ok = users["jack"]
  if ok {
    fmt.Println("jack lives in", city)
  } else {
    fmt.Println("jack is not in the map")

In this statement, the first value (city) is assigned the value stored under the key "bob". If that key doesn’t exist, city is the value type’s zero value ("" empty string). The second value (ok) is a bool that is true if the key exists in the map, and false if not.

This code outputs the following

bob lives in New York
jack is not in the map

You can also run this yourself on the Golang Playground

Join the Golang Developers Community on Golang Cafe