Go course

MapsChecking Whether a Key Exists: Comma-ok

Go

Display

Theme

Maps · Test exercise

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") if judul (the title) isn't in the catalog,
  • "sedang dipinjam semua" ("all copies are on loan") if the title exists but its stock is 0,
  • "tersedia N eksemplar" ("N copies available") if the stock is more than 0 (replace N with the number, for example "tersedia 3 eksemplar").

Use the comma-ok idiom, and fmt.Sprintf to build the text.

main.go
package main

import "fmt"

func cekBuku(katalog map[string]int, judul string) string {
	// TODO: gunakan comma-ok untuk membedakan "tidak ada" dan "stok 0"
	jumlah := katalog[judul]
	return fmt.Sprintf("tersedia %d eksemplar", jumlah)
}

func main() {
	katalog := map[string]int{
		"Laskar Pelangi": 3,
		"Bumi Manusia":   0,
	}
	fmt.Println(cekBuku(katalog, "Laskar Pelangi"))
	fmt.Println(cekBuku(katalog, "Bumi Manusia"))
	fmt.Println(cekBuku(katalog, "Harry Potter"))
}

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)