18.5 Other Standard Collection Types
Beyond the three main types, Rust’s standard library (std::collections
) offers several other useful collections:
BTreeMap<K, V>
: A map implemented using a B-Tree. UnlikeHashMap
,BTreeMap
stores keys in sorted order. Operations (insert, get, remove) haveO(log n)
time complexity. It’s useful when you need to iterate over key-value pairs in sorted key order or perform range queries. Keys must implement theOrd
trait (total ordering) in addition toEq
.HashSet<T>
/BTreeSet<T>
: Set collections that store unique elementsT
.HashSet<T>
uses hashing (likeHashMap
) for averageO(1)
insertion, removal, and membership checking (contains
). Elements must implementEq
andHash
. Order is arbitrary.BTreeSet<T>
uses a B-Tree (likeBTreeMap
) forO(log n)
operations and stores elements in sorted order. Elements must implementOrd
andEq
. Both are useful for efficiently checking if an item exists in a collection, removing duplicates, or performing set operations (union, intersection, difference).
VecDeque<T>
: A double-ended queue (deque) implemented using a growable ring buffer. It provides efficient amortizedO(1)
push and pop operations at both the front and the back of the queue. Accessing elements by index is possible but can beO(n)
in the worst case if the element is far from the ends in the ring buffer layout. Useful for implementing FIFO queues, LIFO stacks (thoughVec
is often simpler for stacks), or algorithms needing efficient access to both ends.LinkedList<T>
: A classic doubly-linked list. It offersO(1)
insertion and removal if you already have a cursor pointing to the node before or after the desired location. It also allows efficient splitting and merging of lists. However, accessing an element by index requires traversing the list (O(n)
), and its node-based allocation pattern generally leads to poorer cache performance compared toVec
orVecDeque
. In idiomatic Rust,LinkedList
is used less frequently thanVec
orVecDeque
, reserved for specific algorithms where its unique properties are genuinely advantageous.BinaryHeap<T>
: A max-heap implementation (priority queue). It allows efficiently pushing elements (O(log n)
) and popping (O(log n)
) the largest element according to itsOrd
implementation. Useful for algorithms like Dijkstra’s or A*, or anytime you need quick access to the maximum item in a collection. Elements must implementOrd
andEq
.
All these standard collections manage their memory automatically and uphold Rust’s safety guarantees through the ownership and borrowing system.