`BTreeSet`
BTreeSet<T> is a sorted set of unique values backed by a B-tree. Membership is O(log n), iteration is in Ord order, and range queries are native.
Detailed Explanation
BTreeSet is to HashSet what BTreeMap is to HashMap. Elements are unique and ordered. iter yields from smallest to largest. range walks a slice of that order. first and last peek at the ends. There is no hash, so there is no HashDoS story and no random seed in your test snapshots.
Use it when the order is part of the problem: unique timestamps you will scan in order, a set of ids you will print deterministically, "the next value after x". Use HashSet when the only question is membership and the type is cheap to hash. The log n cost is the tax you pay for order.
Elements need Ord. The order must stay consistent with Eq. If you implement Ord by one field and Eq by another, the tree's search will not find values it inserted. Derive both whenever you can.
The algebra methods match HashSet: union, intersection, difference, symmetric_difference, is_subset. Because both sets are sorted, those algorithms can run in linear time in the two sizes by walking both iterators, which is the textbook merge. A HashSet intersection hashes instead.
BTreeSet is not a heap. The smallest element is at the left of the tree, but popping it repeatedly is not as cheap as BinaryHeap::pop for a priority-queue workload. If you need "repeatedly take the minimum and insert more", a BinaryHeap (or a BTreeMap of queues) is the clearer tool.
When you reach for BTreeSet: sorted uniqueness, ranges, deterministic iteration. When you reach for HashSet: unordered membership. When you reach for BinaryHeap: priority, not uniqueness-plus-order.
Code Examples
use std::collections::BTreeSet;
fn main() {
let mut ids = BTreeSet::new();
ids.insert(30);
ids.insert(10);
ids.insert(20);
let listed: Vec<_> = ids.iter().copied().collect();
println!("{listed:?}"); // prints: [10, 20, 30]
let mid: Vec<_> = ids.range(10..=20).copied().collect();
println!("{mid:?}"); // prints: [10, 20]
}Common Gotchas
`Ord` must agree with `Eq`
A hand-written pair of impls is a common source of "I inserted it and `contains` is false".
Not a replacement for `BinaryHeap`
Repeatedly removing `first` from a `BTreeSet` works and is slower and more allocation-heavy than a heap for priority queues.
Deterministic iteration is a feature
Prefer `BTreeSet` in tests and serialised snapshots when you would otherwise sort a `HashSet` every time.
Range bounds exclude or include like slices
`range(a..b)` skips `b`. Write `..=` when you mean inclusive.