`HashSet`
HashSet<T> is a hash table of unique values. Insert, remove, and membership tests are average O(1). It is a HashMap<T, ()> with a set-shaped API.
Detailed Explanation
A set answers "have I seen this?" HashSet stores each value once, hashed. insert returns true if the value was new. contains is the membership test. remove deletes and returns whether it was present. There is no associated value; if you need one, you wanted a HashMap.
The same hasher and HashDoS story as HashMap applies. The same Eq + Hash contract applies. Iteration order is not insertion order and not sorted. Two sets compare equal with == if they contain the same elements, regardless of order.
Set algebra is implemented as methods and operators: union, intersection, difference, symmetric_difference, plus |, &, -, ^ on references. Those adapters are lazy iterators. Collect them if you need a new set. is_subset and is_disjoint answer the boolean questions without building a third set.
HashSet is the de-duplicator. iter.collect::<HashSet<_>>() drops duplicates. If you need de-duplication and insertion order, the indexmap crate's IndexSet is the usual next step. If you need sorted unique values, BTreeSet. If n is tiny, a Vec plus contains may be faster because it does not hash.
Capacity works like HashMap. HashSet::with_capacity(n) avoids rehashes while you insert a known batch. reserve is the same call. Rehashing invalidates nothing you should have been holding — there are no stable element pointers — but it is extra work you can skip.
When you reach for HashSet: membership and uniqueness for unordered data. When you reach for BTreeSet: sorted unique data or range queries on the elements. When you reach for HashMap: each key has a value. When you reach for Vec plus sort plus dedup: you needed sorted unique values once, not a live set.
Code Examples
use std::collections::HashSet;
fn main() {
let mut seen = HashSet::new();
assert!(seen.insert("ada"));
assert!(!seen.insert("ada"));
println!("{}", seen.contains("ada")); // prints: true
let a: HashSet<_> = [1, 2, 3].into();
let b: HashSet<_> = [3, 4].into();
let both: HashSet<_> = a.intersection(&b).copied().collect();
println!("{both:?}"); // prints: {3}
}Common Gotchas
`insert` returns whether the value was new
Ignoring the `bool` is fine when you do not care. Do not call `contains` then `insert`; `insert` already tells you.
Iteration order is unstable
Do not snapshot a `HashSet` in a test without sorting. Collect to a `Vec` and sort, or use `BTreeSet`.
A custom `Hash` that ignores fields used in `Eq` is broken
Derive both, or write both to the same fields.
Union adapters are lazy
`a.union(&b)` does not allocate a set. Collect it, or walk it.