HashSet. In Rust the HashSet is a set collection—it has only keys, and no values. There are some differences in function names, but it is based on the same code as HashMap.
Code that uses HashSet can always use HashMap instead, but HashSet can lead to more elegant (and sometimes more maintainable) Rust programs.
Example. This Rust program creates a HashSet, and then calls contains() on the set to see if an element is present in it. Most programs that use HashSet will use contains().
Part 1 We create a new HashSet and call insert() to add 2 keys to it—this is the same as we would do for HashMap.
Part 2 To see if an element exists in the set, we use the contains function. We must pass a reference to this function.
Part 3 As with HashMap, we can acquire the count of keys in the set by calling len.
use std::collections::*;
fn main() {
// Part 1: create a HashSet.
let mut set = HashSet::new();
set.insert(10);
set.insert(20);
// Part 2: Call contains to see if an item exists.
if set.contains(&20) {
println!("CONTAINS 20");
}
// Part 3: Print length.
println!("{}", set.len());
}CONTAINS 20
2
Complex example. In real programs, HashSet will often need to be created from a vector or other data source. We can create and use HashSets in a variety of ways.
Part 1 We have a 2-element vector, and we create a HashSet from it. We add each individual element in a for-loop.
Part 2 HashSet provides a from() method and we can use this to build a HashSet from an array in a single statement.
Part 3 Set operators are available on the HashSet. Here we use intersection, which returns the elements found in both sets.
Part 4 The union is the group of elements found in either set. This effectively combines the 2 HashSets into one.
use std::collections::*;
fn main() {
// Part 1: place elements from a vector into a HashSet.
let vector = vec![10, 20];
let mut set1 = HashSet::new();
for v in vector {
set1.insert(v);
}
// Part 2: create a HashSet from an array.
let set2 = HashSet::from([20, 30, 40]);
// Part 3: compute intersection of 2 sets.
let intersection = set1.intersection(&set2);
for element in intersection {
println!("INTERSECTION: {}", element);
}
// Part 4: compute union of 2 sets.
let u = set1.union(&set2);
for element in u {
println!("UNION: {}", element);
}
}INTERSECTION: 20
UNION: 40
UNION: 30
UNION: 20
UNION: 10
Summary. HashSet can be used when a HashMap is required, but no values are necessary. This can be more elegant than just using a bool or other value inside a HashMap as a placeholder.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.