Maps in Go
By Flavio Copes
Learn how to use maps in Go, the dictionary or hash map type. Create one with make, add and read values by key, and remove items with delete().
A map is a very useful data type in Go. It stores key-value pairs: you save a value under a key, and later you use that key to get the value back.
In other languages it’s also called dictionary or hash map or associative array.
How to create a map
Here’s how you create a map:
agesMap := make(map[string]int)
This map uses strings as keys and ints as values. You don’t need to set how many items the map will hold. It grows as needed.
You can also initialize the map with values directly using this syntax:
agesMap := map[string]int{"flavio": 39}
Adding and reading values
You can add a new item to the map in this way:
agesMap["flavio"] = 39
You can get the value associated with a key using:
age := agesMap["flavio"]
If the key does not exist, you get the zero value of the value type. For an int that’s 0, for a string that’s "".
This can be ambiguous. Is the age really 0, or is the key just missing? To tell the difference, ask for the second return value:
age, ok := agesMap["andrea"]
fmt.Println(age, ok) //0 false
ok is true when the key exists, false when it doesn’t. This is called the comma ok idiom, and you’ll see it everywhere in Go code.
Deleting and counting items
You can delete an item from the map using the delete() function in this way:
delete(agesMap, "flavio")
Deleting a key that doesn’t exist is fine, nothing happens.
You get the number of items in a map with len():
len(agesMap)
Iterating over a map
Use range to loop over all the key-value pairs:
for name, age := range agesMap {
fmt.Println(name, age)
}
Notice that Go does not guarantee the iteration order. Run the same loop twice and you might get the items in a different order. If you need a stable order, put the keys in a slice, sort it, and loop over that.
Be careful with nil maps
Here’s the pitfall that bites everyone at least once. If you declare a map without initializing it, you get a nil map:
var agesMap map[string]int
agesMap["flavio"] = 39 //panic: assignment to entry in nil map
Reading from a nil map is fine (you get the zero value), but writing to it crashes your program.
The fix is to always initialize the map with make() or with a map literal before writing to it.