Rust HashSet
HashSet
In the HashMap chapter, you stored keys together with values. Sometimes you only need a list of values, where each value can only appear once. For example, the names of the players who have joined a game, or the countries you have visited.
For this, Rust has the HashSet. A HashSet is a collection of unique values. If you add a value that is already in the set, it is not added again.
Just like HashMap, you must import HashSet from Rust's standard library:
use std::collections::HashSet;
Create a HashSet
Use HashSet::new() to create an empty set, and the insert() method to add values:
Example
let mut fruits = HashSet::new();
fruits.insert("apple");
fruits.insert("banana");
fruits.insert("apple");
println!("The set has {} fruits.", fruits.len());
Try it Yourself »
We added three values, but "apple" was added two times. A HashSet only keeps one of each value, so the set has 2 fruits.
The len() method returns the number of values in the set, just like it does for vectors.
Add Values
The insert() method also tells you if the value was added. It returns true if the value is new, and false if the value was already in the set:
Example
let mut players = HashSet::new();
println!("{}", players.insert("John")); // true
println!("{}", players.insert("Liam")); // true
println!("{}", players.insert("John")); // false
Try it Yourself »
This is useful when you want to know if something happens for the first time, like a new player joining a game.
Check if a Value Exists
Use the contains() method to check if a value is in the set. It returns true or false:
Example
let mut countries = HashSet::new();
countries.insert("Norway");
countries.insert("Japan");
countries.insert("Brazil");
if countries.contains("Japan") {
println!("You have visited Japan.");
}
println!("Visited Spain? {}", countries.contains("Spain"));
Try it Yourself »
Remove Values
To remove a value from a HashSet, use the remove() method:
Example
let mut countries = HashSet::new();
countries.insert("Norway");
countries.insert("Japan");
countries.insert("Brazil");
countries.remove("Japan");
println!("Countries left: {}", countries.len());
println!("Visited Japan? {}", countries.contains("Japan"));
Try it Yourself »
Loop Through a HashSet
You can use a for loop to go through all the values in a set. In this example, the score 10 is added two times, but it is only counted once:
Example
let mut scores = HashSet::new();
scores.insert(10);
scores.insert(20);
scores.insert(10);
scores.insert(30);
let mut total = 0;
for score in &scores {
total += score;
}
println!("Total of unique scores: {}", total);
Try it Yourself »
Note: A HashSet does not keep its values in any order. If you print the values in a loop, or print the whole set with {:?}, the order can change each time you run the program. In the example above, the order does not matter, because the values are only added together.
Values in Both Sets
You can compare two sets:
intersection()gives the values that are in both setsunion()gives all the values from both sets, without duplicates
Example
let mut john = HashSet::new();
john.insert("chess");
john.insert("football");
let mut jenny = HashSet::new();
jenny.insert("chess");
jenny.insert("tennis");
for hobby in john.intersection(&jenny) {
println!("Both like {}", hobby);
}
println!("Hobbies in total: {}", john.union(&jenny).count());
Try it Yourself »
John and Jenny both like chess, so chess is printed. Together, they have three different hobbies: chess, football and tennis. The count() method counts the values.
Vector, HashMap or HashSet?
- Use a vector when the order matters, or when the same value can appear many times
- Use a HashMap when you want to find a value by its key
- Use a HashSet when each value should only appear once, and you want to check quickly if a value exists