Maps are unordered collection of key value pairs. In other languages they are known with various names viz. hash tables, dictionaries and associative arrays. Here’s an example of a Key-Value pair – Working Days of the week denoted by integer keys.
In the above table Key = 1 denotes a value of Monday. Key = 3 denotes a value of Wednesday.
Let us see how we can represent the above using Go Maps:
How to Declare a Map?
day := make(map[int]string)
You can read this as the variable day is a map of int keys to string values.
Here we’ve used builtin make function with Key type as int and value type as string as shown above. Assigning and fetching values are similar to simple Arrays.
Important Note: Maps are reference types. So, the value of the variable day above is nil. It doesn’t point to an initialized map.
The above Code-Snippet# 1 can be made shorter and precise as follows:
The output of the Code-Snippet# 2 (shared above) is exactly same as what we have seen for Code-Snippet# 1.
Let us see some more interesting operations with Golang Maps. Read the comments to easily understand the code.
Map: map[1:Monday 2:Tuesday 3:Wednesday 4:Thursday 5:Friday] Length of the map: 5 Does Key 6 Exist: false Map: map[5:Friday 1:Monday 2:Tuesday 4:Thursday] Length of the map: 4 Does Key 3 Exist: false
You can find a few more beginner level code examples of Go Maps here. Please comment with your feedback.