×

go · level 2 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

The form tells you whether a key is there.

A missing key gives the zero value, but sometimes zero is a real answer. If stock["pears"] gives 0, are the pears sold out, or does the shop not sell pears at all?

Catch a second value to find out: count, ok := stock["pears"]. ok is a bool that is true only when the key is in the map. Programmers call this the comma ok form.

It often goes inside an if, as a before the condition: if count, ok := stock["pears"]; ok {. The semicolon separates the two parts, and count can only be used inside that if and its else.

package main
import "fmt"
func main() {
	stock := map[string]int{"apples": 12, "pears": 0}
	count, ok := stock["pears"]
	fmt.Println(count, ok)
	count, ok = stock["plums"]
	fmt.Println(count, ok)
}

The name ok is only a habit, but every Go programmer recognises it at a glance.