Queues and heaps
Quick answer
A queue handles work in arrival order, while a priority queue chooses work by priority. Rust provides VecDeque for efficient operations at both ends and BinaryHeap for highest-first priority removal.
FIFO versus priority
Use push_back and pop_front for first-in-first-out processing. BinaryHeap returns its greatest element with pop; it is not a fully sorted list. Both removal methods return Option because a collection can be empty.
use std::collections::VecDeque;fn main() { let mut q = VecDeque::new(); q.push_back("A"); q.push_back("B"); println!("{:?}", q.pop_front());}Expected stdout (not executed):
Some("A")A arrived first.
use std::collections::BinaryHeap;fn main() { let mut jobs = BinaryHeap::from([2, 9, 4]); println!("{:?} {:?}", jobs.pop(), jobs.pop());}Expected stdout (not executed):
Some(9) Some(4)The greatest remaining number is removed first.
Common mistake
Iterating a heap does not guarantee priority order; pop repeatedly when removal order matters.
Try it yourself
Model three incoming requests and compare arrival order with priority order.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Queues and heaps — practice quiz
Choose one answer per question, then review the explanation.
After push_back(3), push_back(9), pop_front on an empty deque, what is returned?
A BinaryHeap contains 2, 10 and 7. What does pop return?
Does iterating a BinaryHeap guarantee descending sorted order?