Go/Maps
From charlesreid1
Go maps are data structures that use a hash table under the hood to provide fast, O(1) lookup of key-value pairs.
Basics
Initialization
To declare a map type, use the notation:
map[KeyType]ValueType
Example: declare a variable that is a map of string keys to integer values:
var m map[string]int
Like pointers/slices, map types are reference types, so if they are not initialized with a value, they have a nil value. A nil map has not been initialized and so has no underlying space in memory, so you cannot write to a nil map.
To initialize space for a map:
m = make(map[string]int)
The make function allocates space in memory for the hash table. It returns a map value pointing to this location in memory. It is important to note that the actual implementation of a map is not specified by the language, so it depends on the implementation of the Go runtime being used.
Working with maps
To set a key value pair:
m["route"] = 66
To look up a key and assign the value to a variable:
i := m["route"]
Unlike Python, if a key does not exist, Go will return the value type's zero value. For integers, the value is 0; for strings, empty string; for booleans, False; etc.
j := m["root"] // j == 0
Two useful built-in functions are length (len) and delete (delete):
// number of items in a map n := len(m) // remove the specified key from the map delete(m, "route")