Getting to Know Maps
A map is a collection of key → value pairs. While a slice is accessed by numeric index 0, 1, 2, ..., a map is accessed by keys you choose yourself, such as a menu item name or a product code.
A map type is written map[TipeKunci]TipeNilai, where TipeKunci is the key type and TipeNilai the value type:
// map literal: langsung diisi
harga := map[string]int{
"espresso": 18000,
"latte": 25000,
}
// map kosong dengan make
stok := make(map[string]int)
The first map is a map literal, filled right away; the second is an empty map created with make. A key can be any type that can be compared with == (string, int, bool, structs made of those types, ...). A slice can't be a key.
Adding, updating, and deleting
harga["mocha"] = 27000 // menambah kunci baru
harga["latte"] = 26000 // mengubah nilai kunci yang sudah ada
delete(harga, "espresso") // menghapus kunci
fmt.Println(len(harga)) // 2 — jumlah pasangan di dalam map
fmt.Println(harga["latte"]) // 26000
Adding and updating use the same syntax: if the key doesn't exist yet, it's created; if it does, it's overwritten. delete on a key that doesn't exist doesn't cause an error; nothing happens. len gives you the number of pairs in the map.
Zero values and nil maps
Reading a key that doesn't exist returns the zero value of the value type (0 for int, "" for string):
fmt.Println(harga["teh"]) // 0
The zero value of a map type itself is nil. Reading from a nil map is safe, but writing to a nil map causes a panic:
var m map[string]int
fmt.Println(m["a"]) // 0, aman
m["a"] = 1 // panic: assignment to entry in nil map
That's why you should always create a map with a literal or make before filling it.
Maps behave like references
When you pass a map to a function, only a "handle" to the same data is copied. Changes made inside the function are visible to the caller:
func diskon(menu map[string]int) {
menu["latte"] = 20000
}
diskon(harga)
fmt.Println(harga["latte"]) // 20000
Task
The "Senja" coffee shop is updating its menu. Complete the perbaruiMenu(menu map[string]int) function, which modifies the map it receives (it doesn't need to return anything):
- Add the menu item
"matcha"priced at28000. - Change the price of
"latte"to27000. - Remove the menu item
"americano".
Then complete menuAwal() map[string]int, which returns a new map containing:
| item | price |
|---|---|
"espresso" | 18000 |
"latte" | 25000 |
"americano" | 20000 |