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:
jualProduk(gudang map[string]Produk, kode string, jumlah int) boolfor an online store. Ifkodedoesn't exist or its stock is less thanjumlah, don't change anything and returnfalse. If there's enough, reduce that product'sStokinside the map and returntrue.catatNilai(rapor map[string]map[string]int, siswa, mapel string, nilai int), which stores the grade inrapor[siswa][mapel]. Create the inner map if the student isn't registered yet.