Start learning free

LESSON 135 OF 679 · DICTIONARIES

Deleting a Key in Rust

Lesson

TL ; DR:

A HashMap's remove method takes a key. It deletes that key and its value.


let mut toys = HashMap::from([("ball", 3), ("doll", 2), ("kite", 1)]);

toys.remove("kite");

println!("{}", toys.len());   // 2


Full lesson:

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

Call remove on the map with the key. The key and its value go away together.

Deleting changes the map. So the map must be declared with let mut.

With a String key in a variable, pass a reference, as in remove(&name).

The length drops by 1. The key is gone, so toys.contains_key("kite") is now false.

remove also returns the deleted value inside an Option. Here that's Some(1). For a missing key it returns None, and nothing changes.

Watch out: after the delete, toys["kite"] panics and stops the program. Check with contains_key first.


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 animals.len() 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