Rust HashSet
In Rust, a HashSet is a collection of unique values stored in a hash table data structure. HashSets provide a way to quickly check if a value is present in the set or not.
Here's an example of how to create and use a HashSet in Rust:
use std::collections::HashSet;
fn main() {
// create a new HashSet of integers
let mut numbers = HashSet::new();
// add some numbers to the HashSet
numbers.insert(1);
numbers.insert(2);
numbers.insert(3);
// check if a value is present in the HashSet
if numbers.contains(&2) {
println!("2 is present in the HashSet");
}
// remove a value from the HashSet
numbers.remove(&3);
// iterate over the values in the HashSet
for number in &numbers {
println!("{}", number);
}
}
In this example, we're creating a new HashSet called numbers using the HashSet::new constructor. We're then inserting three integers into the HashSet using the insert method.
We're using the contains method to check if the value 2 is present in the HashSet and printing a message to the console if it is. We're also using the remove method to remove the value 3 from the HashSet.
Finally, we're iterating over the remaining values in the HashSet using a for loop and printing each value to the console using the println! macro.
HashSets in Rust provide a fast and efficient way to store and look up unique values, making them useful in a wide range of applications. Rust also provides a HashSet::with_capacity method for pre-allocating space for a HashSet if you know how many values it will contain.
