Go course

MapsIterating over Maps and Key Order

Go

Display

Theme

Maps · Output exercise

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:

  1. collect all the keys into a slice,
  2. sort that slice,
  3. 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
main.go
package main

import "fmt"

func main() {
	inventaris := map[string]int{
		"ramuan penyembuh": 5,
		"perisai kayu":     1,
		"anak panah":       30,
		"roti":             8,
		"batu sihir":       2,
	}

	fmt.Println("Inventaris:")

	// TODO: urutan di bawah ini acak! Kumpulkan kunci ke slice,
	// urutkan dengan sort.Strings (jangan lupa import "sort"),
	// lalu cetak "nama: jumlah" mengikuti urutan slice.
	for nama, jumlah := range inventaris {
		fmt.Printf("%s: %d\n", nama, jumlah)
	}

	// TODO: cetak "Total item: N"
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)