[Golang (Go) Tutorial] Maps
Maps
Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
Create a map
1 | var m map[string]int // nil map of string-int pairs |
-
A map (or dictionary) is an unordered collection of key-value pairs, where each key is unique.
-
You create a new map with a make statement or a map literal.
-
The default zero value of a map is nil. A nil map is equivalent to an empty map except that elements can’t be added.
-
The len function returns the size of a map, which is the number of key-value pairs.
Warning: If you try to add an element to an uninitialized map you get the mysterious run-time error Assignment to entry in nil map.
Set, Get, Delete, Length keys/values,
1 | m := make(map[string]float64) |
When you index a map you get two return values; the second one (which is optional) is a boolean that indicates if the key exists.
If the key doesn’t exist, the first value will be the default zero value.
For-each range loop
1 | m := map[string]float64{ |
Iteration order is not specified and may vary from iteration to iteration.
-
If an entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced.
-
If an entry is created during iteration, that entry may or may not be produced during the iteration.
Starting with Go 1.12, the fmt package prints maps in key-sorted order to ease testing.
Performance and implementation
Maps are backed by hash tables.
Set, get and delete operations run in constant expected time. The time complexity for the add operation is amortized.
The comparison operators ==
and !=
must be defined for the key type.
References
Go - Maps - Tutorialspoint - https://www.tutorialspoint.com/go/go_maps.htm
Go map - working with maps in Golang - https://zetcode.com/golang/map/