Go course

MapsNested Maps and Maps of Structs

Go

Display

Theme

Maps · Test exercise

Nested Maps and Maps of Structs

A map's values can be of any type, including structs or other maps.

Maps of structs

type Produk struct {
	Nama  string
	Harga int
	Stok  int
}

gudang := map[string]Produk{
	"KPI-01": {Nama: "Kopi Arabika 250g", Harga: 65000, Stok: 12},
	"TEH-07": {Nama: "Teh Melati", Harga: 18000, Stok: 40},
}

There's one trap: you can't change a struct field directly inside a map.

gudang["KPI-01"].Stok = 10 // error kompilasi: cannot assign to struct field in map

That line is a compile error. Values stored in a map don't have a fixed address, so Go doesn't allow it. The right pattern: take a copy, change it, then store it back.

p := gudang["KPI-01"]
p.Stok -= 2
gudang["KPI-01"] = p

(In Chapter 11 you'll see an alternative: map[string]*Produk.)

Nested maps

A map inside a map fits two-level data, such as report card grades per student per subject:

rapor := map[string]map[string]int{
	"Ani": {"matematika": 90, "biologi": 85},
}
fmt.Println(rapor["Ani"]["biologi"]) // 85

The inner map also has to be created before you fill it. If the student isn't there yet, rapor["Budi"] is nil, and writing rapor["Budi"]["fisika"] = 70 will panic. Check first with comma-ok:

nilai, ok := rapor["Budi"]
if !ok {
	nilai = make(map[string]int)
	rapor["Budi"] = nilai
}
nilai["fisika"] = 70

Because maps behave like references, changing nilai is the same as changing the map stored in rapor["Budi"].

Task

Complete the following two functions:

  1. jualProduk(gudang map[string]Produk, kode string, jumlah int) bool for an online store. If kode doesn't exist or its stock is less than jumlah, don't change anything and return false. If there's enough, reduce that product's Stok inside the map and return true.
  2. catatNilai(rapor map[string]map[string]int, siswa, mapel string, nilai int), which stores the grade in rapor[siswa][mapel]. Create the inner map if the student isn't registered yet.
main.go
package main

import "fmt"

type Produk struct {
	Nama  string
	Harga int
	Stok  int
}

func jualProduk(gudang map[string]Produk, kode string, jumlah int) bool {
	// TODO: cek keberadaan & stok, lalu ambil salinan, ubah, simpan kembali
	return false
}

func catatNilai(rapor map[string]map[string]int, siswa, mapel string, nilai int) {
	// TODO: buat map bagian dalam jika belum ada, lalu simpan nilai
}

func main() {
	gudang := map[string]Produk{
		"KPI-01": {Nama: "Kopi Arabika 250g", Harga: 65000, Stok: 12},
	}
	fmt.Println(jualProduk(gudang, "KPI-01", 2), gudang["KPI-01"].Stok)

	rapor := map[string]map[string]int{}
	catatNilai(rapor, "Budi", "fisika", 70)
	fmt.Println(rapor)
}

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)