Start learning free

LESSON 130 OF 671 · DICTIONARIES

Reading a Key That May Be Missing in Go

Lesson

TL ; DR:

A missing key gives the zero value, 0 for an int. So m[key] already reads with 0 as the default.


points := map[string]int{"Ana": 7}

fmt.Println(points["Ana"])   // 7
fmt.Println(points["Ben"])   // 0


Full lesson:

A missing key often means "none yet". A player with no points yet has 0 points.

As Maps & the ok Idiom showed, Go never fails on a missing key.

A lookup like points["Ben"] gives 0, the zero value of an int.

So when 0 is the default you want, a plain lookup is enough.

Reading this way doesn't add the key. points still has one key afterwards.

The zero value of a string is "", and of a bool it is false.

When you need another default, use comma-ok. Here a missing key gives -1:

score, ok := points["Ben"]
if !ok {
    score = -1
}

Your task

stock counts the fruit in a shop. The code reads and prints the pears.

There are no plums yet. Read "plums" with a plain lookup. Store it in plums.

Then print the plums line, the same way as the pears line.

Expected output:

We have 2 pears
We have 0 plums
STEP 1 OF 2
    Ctrl + Enter to check