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.
|
|
or we could do it all in one line like so…
|
|
And of course to retrieve the value you would simply do the following.
|
|
Checking if the key exists
The best and simplest way to check if the key in a map exists is the following.
|
|
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.
|
|
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.