When you try to access the value of a key that does not exist on map, the zero value for the type of the entries in the map is what you get back. This is not very useful for distinguishing between a key that exists in the map but is explicitly assigned to the zero value of the type, and one that does not exists at all.
In such situations, it is necessary to use what is known as an index expression to check if the specified key exists. Here’s how it works:
if statements in Go can include a condition and an initialisation statement as shown above. The
exists variables are bound to the scope of the
if block (including the any
else if blocks) so you cannot access them outside this block. If you need to access the value outside the
if block, you need to declare the variables outside as well:
exists variable will be
true if the specified key exists in the map. Otherwise, it will be
false. Some people prefer to use
found as the naming convention for the second variable instead of
If you only want to check if a key exists without caring about its actual value, just assign the value to the blank operator (
_). This has the effect of discarding the value.
Thanks for reading, and happy coding!