Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust HashSet


Share

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 sets
  • union() 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


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.