Maps
Maps (dictionaries, hash maps). Initializing a map can be done literally or via the make
function.
We access the map (with the key) and insert/update values as shown below:
We can remove a key with the delete
method.
We can get the size of a map using the len
method, i.e. len(m)
.
If we access a key that does not exist, Go returns a zeroed value. There are 3 possibilities when we access a map:
- Key exists
- Key does not exists
- Key exists with an zeroed value or Key does not exist and hence there a zeroed value is returned (ambiguous)
To prevent the ambiguity in the 3rd case, we use this syntax: elem , ok := m[key]
. The returned variable ok
is a boolean type which indicates if the key was present or not.
There is no order to it, iterating over a map does not guarantee any particular order.
Passing maps to a function passes the pointer of the map. Modifying the map within a function will modify the original map.
#
Range OperationThe range
keyword is used to iterate on slices and maps. The range operation returns two values for every iteration - first is the index and second is the element at that index.
Exercise!
Create a map, iterate over it using the range operation and print them out to the console.