Iterating over Maps and Key Order
You can walk through a map with for ... range, just like a slice. The difference is that you get the key and the value:
inventaris := map[string]int{
"ramuan": 5,
"pedang": 1,
"panah": 30,
}
for nama, jumlah := range inventaris {
fmt.Println(nama, jumlah)
}
for nama := range inventaris { // hanya kunci
fmt.Println(nama)
}
The second loop takes only the keys.
Iteration order is random
Go deliberately doesn't guarantee the iteration order of a map. Run the program above a few times and the order may change. Never write code that depends on the order of a range over a map.
If you need output that's always the same (for a report or a test, say), here's how:
- collect all the keys into a slice,
- sort that slice,
- iterate over the sorted slice, then look up each value in the map.
import (
"fmt"
"sort"
)
kunci := make([]string, 0, len(inventaris))
for nama := range inventaris {
kunci = append(kunci, nama)
}
sort.Strings(kunci) // urut abjad: panah, pedang, ramuan
for _, nama := range kunci {
fmt.Println(nama, inventaris[nama])
}
The sort package is covered in more detail in Chapter 12. For now, just remember that sort.Strings sorts a []string and sort.Ints sorts an []int in place (the slice itself is changed; nothing is returned).
Task
The program holds an RPG character's inventory. Complete main so that it prints each item in alphabetical order in the format nama: jumlah (name: quantity), followed by a line with the total quantity of all items.
Expected output:
Inventaris:
anak panah: 30
batu sihir: 2
perisai kayu: 1
ramuan penyembuh: 5
roti: 8
Total item: 46