Search⌘ K

Existence of Key-Value Item

Understand how to verify if a key exists in a Go map using the comma ok idiom, differentiate between zero values and absent keys, and learn to delete keys safely without errors. This lesson helps you manage map key-value data accurately.

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 ...