Start learning free

LESSON 134 OF 679 · DICTIONARIES

Reading a Key That May Be Missing in Rust

Lesson

TL ; DR:

*map.get(key).unwrap_or(&0) gives the key's value, or 0 when the key is missing.


let points = HashMap::from([("Ana", 7)]);

println!("{}", *points.get("Ana").unwrap_or(&0));   // 7
println!("{}", *points.get("Ben").unwrap_or(&0));   // 0


Full lesson:

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

points["Ben"] can't say that. It panics.

get gives an Option, as in Option & Some. It is Some(&7) for Ana and None for Ben.

unwrap_or(&0) takes the reference inside, or a reference to 0. The * in front turns it into a plain number.

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

With a String key in a variable, pass &name to get.


Your task

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

There are no plums yet. Read "plums" with get and unwrap_or(&0). 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