collections
Two containers that Vec, Map and Set (built in, no import) do not cover: Queue, a first-in-first-out queue, and Heap, a priority queue.
Use Queue when items are added at one end and taken from the other (work lists, breadth-first search). Taking from the front of a Vec costs O(n); Queue.pop costs O(1) on average. Use Heap when you always want the smallest item next (schedulers, shortest-path search, “top k” problems). For a sorted list you build once, Vec.sort plus binary_search or insert_sorted is often simpler.
Breadth-first search with a Queue:
import collections
let edges = Map { 1: [2, 3], 2: [4], 3: [4], 4: [] }let mut seen: Set<i64> = Set.new()let mut queue: collections.Queue<i64> = collections.Queue.new()let mut order: Vec<Str> = []queue.push(1)seen.insert(1)while true { match queue.pop() { Some(node) => { order.push(node.to_str()) for next in edges.get(node).unwrap() { if !seen.contains(*next) { seen.insert(*next) queue.push(*next) } } } None => break }}print(order.join(" "))1 2 3 4A Heap of your own type. The type must implement Order; compare returns a negative number, zero or a positive number. pop gives the smallest first:
import collections
struct Job { priority: i64 name: Str}
impl Order for Job { fn compare(&self, other: &Job) -> i64 { return self.priority.compare(&other.priority) }}
let mut jobs: collections.Heap<Job> = collections.Heap.new()jobs.push(Job { priority: 3, name: "write docs" })jobs.push(Job { priority: 1, name: "fix crash" })jobs.push(Job { priority: 2, name: "review" })while !jobs.is_empty() { let job = jobs.pop().unwrap() print(f"{job.priority} {job.name}")}1 fix crash2 review3 write docsLargest first: wrap each item in Reverse, and read it back through .value:
import collections
let mut h: collections.Heap<collections.Reverse<Str>> = collections.Heap.new()for word in ["pear", "apple", "zucchini"] { h.push(collections.Reverse { value: word })}while !h.is_empty() { print(h.pop().unwrap().value)}zucchinipearappleReference
Section titled “Reference”import collectionspub struct Queue<T> {}First in, first out; adding or taking at either end costs O(1) on average.
Has push and pop for normal queue use, plus push_front and pop_back, so it also works as a double-ended queue or a stack. peek and peek_back look at the oldest and newest item without taking them; there is no indexing or iteration.
It also has 2 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Queue.new
Section titled “Queue.new”pub fn new() -> Queue<T>Queue.len
Section titled “Queue.len”pub fn len(&self) -> i64Queue.is_empty
Section titled “Queue.is_empty”pub fn is_empty(&self) -> boolQueue.push
Section titled “Queue.push”pub fn push(&mut self, item: T)Adds at the back; pop takes from the front.
Queue.push_front
Section titled “Queue.push_front”pub fn push_front(&mut self, item: T)Queue.pop
Section titled “Queue.pop”pub fn pop(&mut self) -> Option<T>Takes the oldest item.
Queue.peek
Section titled “Queue.peek”pub fn peek(&self) -> Option<&T>The oldest item, without taking it.
Queue.peek_back
Section titled “Queue.peek_back”pub fn peek_back(&self) -> Option<&T>The newest item, without taking it.
Queue.pop_back
Section titled “Queue.pop_back”pub fn pop_back(&mut self) -> Option<T>Takes the newest item.
pub struct Heap<T: Order> {}A priority queue: pop always gives the smallest item (by Order); push and pop cost O(log n).
T must implement Order. Numbers, Str, and tuples of ordered items do, so a (priority, name) pair works without a struct of its own. Tuples compare item by item, so ties on the first item are settled by the second.
import collections
let mut h: collections.Heap<(i64, Str)> = collections.Heap.new()h.push((2, "review"))h.push((1, "fix bug"))h.push((1, "answer mail"))while !h.is_empty() { let (p, task) = h.pop().unwrap() print(f"{p} {task}")}1 answer mail1 fix bug2 reviewIt also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.
Heap.new
Section titled “Heap.new”pub fn new() -> Heap<T>Heap.len
Section titled “Heap.len”pub fn len(&self) -> i64Heap.is_empty
Section titled “Heap.is_empty”pub fn is_empty(&self) -> boolHeap.push
Section titled “Heap.push”pub fn push(&mut self, item: T)Heap.peek
Section titled “Heap.peek”pub fn peek(&self) -> Option<&T>The smallest item without taking it.
Returns a reference, so the heap cannot change while you hold it. Clone or copy what you need before calling push or pop.
Heap.pop
Section titled “Heap.pop”pub fn pop(&mut self) -> Option<T>Takes the smallest item; among equal items, which comes first is not defined.
Items that compare equal come out in no particular order. If order matters for ties (for example first come, first served), add a sequence number to the item and compare on it second.
Reverse
Section titled “Reverse”pub struct Reverse<T: Order> { pub value: T}Wraps a value to reverse its order, so a Heap<Reverse<T>> gives the largest item first.
Reverse.compare
Section titled “Reverse.compare”fn compare(&self, other: &Reverse<T>) -> i64