Start learning free

LESSON 241 OF 679 · SETS

Removing from a Set and Looping Over It in Rust

Lesson

TL ; DR:

remove(&x) takes x out of a set. A for loop over &s visits every value once, in no fixed order.


let mut colors: HashSet<&str> = vec!["red", "blue", "green"].into_iter().collect();

colors.remove("blue");

colors.remove("pink");          // not in it, nothing happens

for color in &colors {
    println!("{}", color);      // red and green, in any order
}


Full lesson:

s.remove(&x) removes x from the set s. It returns true if x was there. If it wasn't, nothing happens and it returns false.

Like contains, remove takes a reference. A string literal like "pink" already is one. For a number, write s.remove(&5).

for x in &s visits each value of the set once. The & borrows the set, so you can still use it after the loop.

The order isn't fixed. Rust may even change it from one run to the next. So loop over a set when the order doesn't matter. A total, a count and a check are fine.

Don't remove values from a set while you loop over it. The compiler refuses, because the loop is borrowing the set. Remove first, then loop.


Your task

In a word game, the set found holds the words a player found. The words "qqq" and "zzz" aren't allowed. Remove both from found.

The player never found "zzz", so removing it changes nothing.

Then add up the points. A word scores one point per letter. Loop over found and add each word's length to score.

The code already prints how many words are left, and the points.

Expected output:

4 words
14 points
STEP 1 OF 3
    Ctrl + Enter to check