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.
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()
.
HashSet
and call insert()
to add 2 keys to it—this is the same as we would do for HashMap
.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
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.
HashSet
from it. We add each individual element in a for
-loop.HashSet
provides a from()
method and we can use this to build a HashSet
from an array in a single statement.HashSet
. Here we use intersection, which returns the elements found in both sets.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
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.