Existence of Key-Value Item

This lesson focuses on two major concepts: how to find a value associated with a key and how to delete a key-value pair from a map.

Testing the existence of a key

We saw in the previous lesson that val1 = map1[key1] returns the value val1 associated with key1. If key1 does not exist in the map, val1 becomes the zero-value for the value’s type, but this is ambiguous. Now we can’t distinguish between this case or the case where key1 does exist and its value is the zero-value! In order to test this, we can use the following comma ok form:

val1, isPresent = map1[key1]

The variable isPresent will contain a Boolean value. If key1 exists in map1, val1 will contain the value for key1, and isPresent will be true. If key1 does not exist in map1, val1 will contain the zero-value for its type, and isPresent will be false.

If you just want to check for the presence of a key and don’t care about its value, you could write:

_, ok := map1[key1] // ok == true if key1 is present, false otherwise

Or combined with an if:

if _, ok := map1[key1]; ok {
  // ...

Deleting an element with a key

This is done with:

delete(map1, key1)

When key1 does not exist, this statement doesn’t produce an error.

Both the techniques are implemented in the following program.

Get hands-on with 1200+ tech skills courses.