rust hashset

Rust HashSet

In Rust, a HashSet is a collection type that stores unique values in no particular order. It is part of the Rust standard library and is defined in the std::collections module. The HashSet is implemented using a hash table, which provides fast insertion, deletion, and lookup operations.

To use a HashSet in Rust, you need to import the HashSet type from the std::collections module. Here's an example of how to create and use a HashSet in Rust:

use std::collections::HashSet;

fn main() {
    // Create a new empty HashSet
    let mut set: HashSet<i32> = HashSet::new();

    // Insert values into the HashSet
    set.insert(1);
    set.insert(2);
    set.insert(3);

    // Check if a value is present in the HashSet
    if set.contains(&2) {
        println!("The value 2 is present in the HashSet");
    }

    // Remove a value from the HashSet
    set.remove(&3);

    // Iterate over the values in the HashSet
    for value in &set {
        println!("Value: {}", value);
    }
}

This example demonstrates how to create a HashSet, insert values into it, check for the presence of a value, remove a value, and iterate over the values in the HashSet.

Note: The HashSet in Rust requires the values to implement the Eq and Hash traits. This means that you can only use types that implement these traits as the element type of a HashSet.

I hope this helps! Let me know if you have any further questions.