Checking Whether a Key Exists: Comma-ok
Remember: reading a key that doesn't exist returns the zero value. That causes a problem. Look at this library catalog:
stok := map[string]int{
"Laskar Pelangi": 3,
"Bumi Manusia": 0,
}
fmt.Println(stok["Bumi Manusia"]) // 0
fmt.Println(stok["Harry Potter"]) // 0
Both return 0, yet they mean different things: one exists but is out of copies, the other isn't in the catalog at all.
The comma-ok idiom
A map access can return two values. The second one (usually named ok) is true if the key really exists:
jumlah, ok := stok["Harry Potter"]
if !ok {
fmt.Println("buku tidak ada di katalog")
}
This form is often combined with the short if statement (Chapter 3):
if jumlah, ok := stok["Bumi Manusia"]; ok {
fmt.Println("stok:", jumlah) // stok: 0
}
If you only want to know whether the key exists, ignore the value with _:
_, ada := stok["Laskar Pelangi"]
The name ok is just a convention, but almost all Go code uses it, so it's easy to recognize.
Task
Complete the cekBuku(katalog map[string]int, judul string) string function for a library app. The map's values are the number of copies available to borrow.
Return:
"tidak terdaftar"("not registered") ifjudul(the title) isn't in the catalog,"sedang dipinjam semua"("all copies are on loan") if the title exists but its stock is0,"tersedia N eksemplar"("N copies available") if the stock is more than 0 (replaceNwith the number, for example"tersedia 3 eksemplar").
Use the comma-ok idiom, and fmt.Sprintf to build the text.