🚀 Get 25% off access to all my premium courses - use discount code FUNCMAIN at checkout - view the pricing page now!

Checking if a Key Exists in a Map in Go Image Checking if a Key Exists in a Map in Go

In this code snippet, we are going to look at how we can check if a key exists within a map in Go. Maps are exceptional when it comes to storing key, value pairs.

When we store a value in a map, we use a hashing function on the key which ultimately results in us getting an index value. This index value represents where in the underlying array a value can be found given there are no collisions.

This lookup method means that we can effectively check to see if a key exists within a map almost instantly. The hashing function that returns an index is executed in O(1) time, whereas if we were to lookup a value within an array/slice, we would have a worst case execution time of O(n) where n is the number of elements within the array.

Execution

When we execute this, we will see the following output:

$ go run main.go
25

When we execute the call to mymap['key'] we get back two distinct values, the first of which is the value of the key and the second is a bool value which represents whether or not the given key exists within the map.

This second value is what we use to check if a given key exists in the if statement on line 13. We first do an assignment using _, ok := mymap["elliot"]; before then using the ok value as a conditional for our if statement.

Only if the value exists in the map does the body of the if statement execute.

Further Reading

If you found this useful and wish to learn more about Maps in Go, then you may also enjoy this full article on Maps: