Rust Guide > Documentation > Collections > HashSet

Introduction

The HashSet class in Rust provides an unordered collection of unique values. It is implemented as a hash table, offering efficient insertion, deletion, and membership testing.

Using HashSet

The HashSet class can be used to create and manage a set of unique values. Here is a basic example:

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(3);
    set.insert(1);
    set.insert(2);
    for value in &set {
        println!("{}", value);
    }
}
// Output (order may vary):
// 1
// 2
// 3

Key Methods

Below are some of the key methods exposed by the HashSet class:

new

Creates a new, empty HashSet.

use std::collections::HashSet;

fn main() {
    let set: HashSet<i32> = HashSet::new();
    println!("Set created.");
}
// Output: Set created.

insert

Adds a value to the set. Returns true if the value was not already present in the set.

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    set.insert(2);
    println!("{:?}", set);
}
// Output (order may vary): {1, 2}

remove

Removes a value from the set. Returns true if the value was present in the set.

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    set.remove(&1);
    println!("{:?}", set);
}
// Output: {}

contains

Checks if the set contains a particular value. Returns true if the value is present.

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    println!("{}", set.contains(&1));
}
// Output: true

len

Returns the number of elements in the set.

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    set.insert(2);
    println!("Set length: {}", set.len());
}
// Output: Set length: 2

iter

Returns an iterator over the elements of the set.

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(3);
    set.insert(1);
    set.insert(2);
    for value in &set {
        println!("{}", value);
    }
}
// Output (order may vary):
// 1
// 2
// 3

Example Usage

Example 1: Basic Usage

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    set.insert(2);
    set.insert(3);
    println!("{:?}", set);
}
// Output (order may vary): {1, 2, 3}

Example 2: Removing Elements

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    set.insert(2);
    set.remove(&1);
    println!("{:?}", set);
}
// Output (order may vary): {2}

Example 3: Checking for Elements

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(1);
    println!("Contains 1: {}", set.contains(&1));
    println!("Contains 2: {}", set.contains(&2));
}
// Output:
// Contains 1: true
// Contains 2: false

Example 4: Iterating Over Elements

use std::collections::HashSet;

fn main() {
    let mut set = HashSet::new();
    set.insert(3);
    set.insert(1);
    set.insert(2);
    for value in &set {
        println!("{}", value);
    }
}
// Output (order may vary):
// 1
// 2
// 3

Example 5: Union of Sets

use std::collections::HashSet;

fn main() {
    let mut set1 = HashSet::new();
    set1.insert(1);
    set1.insert(2);

    let mut set2 = HashSet::new();
    set2.insert(2);
    set2.insert(3);

    let union_set: HashSet<_> = set1.union(&set2).cloned().collect();
    println!("{:?}", union_set);
}
// Output (order may vary): {1, 2, 3}

Considerations

  • The HashSet does not maintain the order of elements, making it unsuitable for applications where order matters.
  • Operations on HashSet are generally faster than those on BTreeSet, especially for large sets, but it does not provide order guarantees.
  • The HashSet relies on the Hash and Eq traits, so custom types used as elements must implement these traits.

See Also

  • BTreeSet - An ordered collection of unique values, providing sorted elements.
  • HashMap - A key-value store based on a hash table.
  • Vec - A contiguous growable array type with heap-allocated contents.
  • LinkedList - A linked list allowing efficient insertion and removal at any point.