Skip to content

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 4

A 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 crash
2 review
3 write docs

Largest 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)
}
zucchini
pear
apple
import collections
pub 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.

pub fn new() -> Queue<T>
pub fn len(&self) -> i64
pub fn is_empty(&self) -> bool
pub fn push(&mut self, item: T)

Adds at the back; pop takes from the front.

pub fn push_front(&mut self, item: T)
pub fn pop(&mut self) -> Option<T>

Takes the oldest item.

pub fn peek(&self) -> Option<&T>

The oldest item, without taking it.

pub fn peek_back(&self) -> Option<&T>

The newest item, without taking it.

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 mail
1 fix bug
2 review

It also has 1 private field(s), so outside this module it is made only by this module’s functions, which check what goes in.

pub fn new() -> Heap<T>
pub fn len(&self) -> i64
pub fn is_empty(&self) -> bool
pub fn push(&mut self, item: T)
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.

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.

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.

fn compare(&self, other: &Reverse<T>) -> i64