Christian Giacomi

How to check if a key exists in a map in Go

Posted — Jul 12, 2022

This post is going to be a simple and short one. When using a map in Go, it is not uncommon for a developer like myself to access the map via an index without checking if the key is actually present in the map. This can lead to some funky outcomes. In other languages accessing an index that is not present in the equivalent data structure usually results in a runtime error of some kind.

In Go things a little different and it is good to know the difference, or one risks of running into some strange behavior.

Map

This is what a map looks like in Go map[KeyType]ValueType and as you already know this is how you assign a value to a map.

m := make(map[int]string)  // Create a map
m[42] = "The Answer to the Ultimate Question of Life, the Universe, and Everything"

or we could do it all in one line like so…

m := map[int]string{42: "The Answer to the..."}

And of course to retrieve the value you would simply do the following.

quote := m[42]
fmt.Printf("%s", m[42])
// output: The Answer to the Ultimate Question of Life, the Universe, and Everything

Checking if the key exists

The best and simplest way to check if the key in a map exists is the following.

if value, keyExists := m[42]; keyExists {
    // The key is present in the map, note that value will be a copy, so any changes you
    // might make to value will only affect the copy.
    fmt.Printf("%s", value)
 } else {
    // The key is NOT present in the map
    fmt.Println("key not present")
}

That’s it… very simple and straight forward. As always it’s very important to write defensive code to ensure one don’t end up in strange situations.

Accessing the map directly

What would happen if one simply ignored the presence of the key in a map and just accessed the map with an invalid key?

The answer is that Go would return the default value for the type defined for the map. Looking at the following example it is clear to see what would happen.

// Map that holds strings values
stringMap := make(map[string]string)
// some initialization code
fmt.Println(stringMap["invalid"])
// Will print an empty string


// Map that holds int values
intMap := make(map[string]int)
// some initialization code
fmt.Println(intMap["invalid"])
// Will print a 0

So Go would simply return an empty string, for a map that is defined like so map[int]string, and a 0 (zero) for a map defined like so map[int]int

It is a completely different story though if you passed in the wrong type for the key. In this case one would get back a compilation error with something that looks like so cannot use "somekey" (untyped string constant) as int value in map index.

If this post was helpful tweet it or share it.

See Also