Start learning free

LESSON 131 OF 671 · DICTIONARIES

Deleting a Key in Go

Lesson

TL ; DR:

The built-in function delete removes a key and its value from a map.


toys := map[string]int{"ball": 3, "doll": 2, "kite": 1}
delete(toys, "kite")

fmt.Println(len(toys))   // 2


Full lesson:

Sometimes an entry has to go. A shop stops selling an item. A player leaves the game.

Call delete with the map, then the key. Like len, it is built into Go. The key and its value go away together.

The length drops by 1. Deleting a key that isn't there does nothing. There is no error.

Watch out: after the delete, toys["kite"] gives 0, the zero value. That looks like a count of 0 kites. Only the comma-ok form tells you the key is gone.

_, ok := toys["kite"]   // ok is false

Your task

A pet shop counts what it has for sale in animals. Each key is a kind of animal. Its value is how many the shop has.

The last rabbit just went home with a family. Delete the key "rabbit" from animals.

Then print len(animals) again. The code at the bottom checks if any rabbits are left.

Expected output:

3
2
No rabbits left
STEP 1 OF 2
    Ctrl + Enter to check