Start learning free

LESSON 237 OF 679 · SETS

Sets in Rust

Lesson

TL ; DR:

A HashSet holds values without repeats. Inserting a value that is already in it changes nothing.


use std::collections::HashSet;

let mut pets: HashSet<&str> = HashSet::new();   // an empty set

pets.insert("cat");

pets.insert("cat");                // already in it, no change

println!("{}", pets.len());        // 1

println!("{}", pets.contains("cat"));   // true


Full lesson:

A Vec keeps every value you put in it, repeats too. Sometimes you only need to know which values there are. A set is made for that.

A set holds each value once. Inserting a value that is already in it changes nothing.

HashSet comes from Rust's standard library. The use line at the top of the sample brings it in. Without it, the compiler doesn't know the name.

  • HashSet::new() makes an empty set. Declare it with let mut to change it.
  • s.insert(x) puts x in the set s. It returns false for a repeat.
  • s.contains(&x) is true when x is in the set. It takes a reference.
  • s.len() gives how many values the set holds.
  • v.into_iter().collect() builds a set from the vector v. Its repeats go in once.

As in Vec & Iterators, collect() needs the type after the name. Write let s: HashSet<&str> = ....

Checking s.contains(&x) is fast, even for a big set. A vector's contains looks at the values one by one.

A set has no order and no indexes. A printed set may show its values in any order.


Your task

The camp's sign-up vector, names, has some names twice. Build a HashSet named kids from it.

Then Zoe signs up, and Ava signs up again. Insert both names into kids.

Last, if kids contains "Leo", print Leo is coming.

The code already prints the number of kids twice.

Expected output:

3 kids
4 kids
Leo is coming
STEP 1 OF 3
    Ctrl + Enter to check