Start learning free

LESSON 229 OF 679 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Looping Over a Dictionary in Rust

Lesson

TL ; DR:

A for loop over a borrowed HashMap, like &stock, visits every entry. (fruit, amount) splits each one into its key and its value.


let stock = HashMap::from([("apples", 5), ("pears", 2)]);

for (fruit, amount) in &stock {
    println!("{} {}", fruit, amount);
}

// pears 2
// apples 5   (in any order)


Full lesson:

A loop can visit every entry of a map, one at a time. The loop body runs once per key.

&stock borrows the map for the loop. Each turn gives a key and its value. The key comes first, then the value.

Both come as references, as in a loop over &nums. Write *amount to get the number itself.

Loop over stock.keys() to get only the keys. Don't need the key? Write _ in its place, as in for (_, amount) in &stock.

The order: a HashMap has no fixed order. It can change from one run to the next. A total or a count comes out the same in any order. Those are safe answers.

Watch out: without the &, the loop takes the map for itself. You can't use stock after such a loop.


Your task

A game keeps each player's points in scores. The variables total and count start at 0.

Loop over scores. Add every player's points to total. Count the players with 10 points or more in count.

The loop needs only the points, not the names. The code at the bottom prints both.

Expected output:

43
2
STEP 1 OF 3
    Ctrl + Enter to check