Go · Stage 5 – Grouping Data · Lesson 34 of 64

Checking Whether a Map Key Exists

Distinguish a missing key from a stored zero value.

Go code

ages := map[string]int{"Maya": 12}
age, ok := ages["Noah"]
fmt.Println(age, ok)
Line-by-line explanation
  1. The map has only Maya.
  2. The lookup requests Noah.
  3. Age receives int’s zero value.
  4. Ok receives false because the key is absent.
Expected output
0 false

This is the expected result.