0Pricing
Learn Rust Coding · Lesson

Working with HashSet

Track unique values.

What Is a HashSet?

A HashSet stores a collection of unique values. There are no duplicates and no keys, just members.

It is great for answering one question fast: "have I seen this value before?"

Creating a Set

Like HashMap, HashSet lives in std::collections and needs a use import.

Create an empty one with HashSet::new() and declare it mut to add items.

use std::collections::HashSet;

fn main() {
    let mut s: HashSet<i32> = HashSet::new();
    s.insert(1);
    s.insert(2);
    println!("size: {}", s.len());
}

All lessons in this course

  1. Building a HashMap
  2. Entry API and Defaults
  3. Working with HashSet
  4. Counting and Grouping
← Back to Learn Rust Coding