Looping over Maps
In The range Loop lesson, range gave you the index and the value of each item in a slice. It works with maps too. On each pass of the loop, you get one key and its value.
package main
import "fmt"
func main() {
stock := map[string]int{
"pens": 12,
"ink": 3,
"paper": 40,
"tape": 7,
}
for name, count := range stock {
fmt.Println(name, count)
}
}
Output:
ink 3
paper 40
tape 7
pens 12
Every pair was printed once. But look at the order. It is not the order of the literal, and it is not sorted either. A map does not keep its keys in any order. Run the program a few times and the order changes. In our runs, the loop sometimes started with pens, sometimes with tape and sometimes with ink. Go does this on purpose, so that nobody writes a program that depends on one order.
When you printed a whole map with fmt.Println in the Maps lesson, the keys were sorted. That is something fmt.Println does for you. A range loop does not sort.
Only the keys, or only the values
If you only need the keys, leave out the second variable:
stock := map[string]int{"pens": 12, "ink": 3}
for name := range stock {
fmt.Println(name)
}
Output:
pens
ink
If you only need the values, write the blank identifier _ in place of the key, as you did with the index of a slice:
total := 0
for _, count := range stock {
total += count
}
fmt.Println("total:", total)
Output:
total: 15
Work that does not care about order
A total is the same in any order. So are the largest value and the number of values that pass a test. Work like this is safe to do in a map loop. Here the loop finds the item with the fewest left in stock:
stock := map[string]int{
"pens": 12, "ink": 3, "paper": 40,
}
low := ""
lowCount := 1000
for name, count := range stock {
if count < lowCount {
low = name
lowCount = count
}
}
fmt.Println(low, lowCount)
Output:
ink 3
This gives the same answer on every run, as long as two items do not share the lowest count. If they do, the loop keeps whichever one it meets first, and that can change from run to run.
Deleting inside the loop
Go allows you to delete keys from a map while you range over it. This removes every item that is sold out:
stock := map[string]int{
"pens": 12, "ink": 0, "glue": 0,
}
for name, count := range stock {
if count == 0 {
delete(stock, name)
}
}
fmt.Println(stock)
Output:
map[pens:12]
When the order of the lines does matter, for example when you print a report, you need to sort the keys first. The next lesson shows how.
In the exercise, range over a map of drivers to find the total of all their minutes and the driver with the most minutes.