I Built a Stack and a Queue in Rust. Then I Deleted Both and Used Vec.
After the linked list article, where the borrow checker fought every design decision, and the binary tree article, where ownership turned out to fit the structure naturally, I expected the stack and queue to land somewhere in the middle. They did not. The stack was almost insultingly easy. The queue started easy and then revealed a performance trap that the standard library quietly solves for you.
The real lesson from both data structures is not about ownership or lifetimes. It is about what Rust’s ownership model implicitly encourages through performance characteristics, and why Vec ends up being the right answer for both unless you have a very specific reason to do otherwise.
The stack
A stack is LIFO: last in, first out. Push something on, pop it off, peek at the top without removing it. The whole thing in Rust:
<button data-code="pub struct Stack {
elements: Vec,
}
impl Stack {
pub fn new() -> Self {
Stack { elements: Vec::new() }
}
pub fn push(&mut self, item: T) {
self.elements.push(item);
}
pub fn pop(&mut self) -> Option {
self.elements.pop()
}
pub fn peek(&self) -> Option {
self.elements.last()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn size(&self) -> usize {
self.elements.len()
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
pub struct Stack<T> {
elements: Vec<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Stack { elements: Vec::new() }
}
pub fn push(&mut self, item: T) {
self.elements.push(item);
}
pub fn pop(&mut self) -> Option<T> {
self.elements.pop()
}
pub fn peek(&self) -> Option<&T> {
self.elements.last()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn size(&self) -> usize {
self.elements.len()
}
}
pub struct Stack<T> {
elements: Vec<T>,
}
impl<T> Stack<T> {
pub fn new() -> Self {
Stack { elements: Vec::new() }
}
pub fn push(&mut self, item: T) {
self.elements.push(item);
}
pub fn pop(&mut self) -> Option<T> {
self.elements.pop()
}
pub fn peek(&self) -> Option<&T> {
self.elements.last()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn size(&self) -> usize {
self.elements.len()
}
}
That is the entire implementation. Push appends to the end of the Vec. Pop removes from the end. Both are O(1) amortised. Peek borrows the last element immutably. There is no interesting ownership story here because Vec already owns its elements, and adding or removing from the end never requires touching anything else in the allocation.
The test suite to verify it behaves correctly:
<button data-code="#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_and_pop() {
let mut stack = Stack::new();
stack.push(1);
stack.push(2);
stack.push(3);
assert_eq!(stack.pop(), Some(3));
assert_eq!(stack.pop(), Some(2));
assert_eq!(stack.pop(), Some(1));
assert_eq!(stack.pop(), None);
}
#[test]
fn peek_does_not_remove() {
let mut stack = Stack::new();
stack.push(42);
assert_eq!(stack.peek(), Some(&42));
assert_eq!(stack.size(), 1); // still there
}
#[test]
fn empty_stack_behaviour() {
let stack: Stack = Stack::new();
assert!(stack.is_empty());
assert_eq!(stack.peek(), None);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_and_pop() {
let mut stack = Stack::new();
stack.push(1);
stack.push(2);
stack.push(3);
assert_eq!(stack.pop(), Some(3));
assert_eq!(stack.pop(), Some(2));
assert_eq!(stack.pop(), Some(1));
assert_eq!(stack.pop(), None);
}
#[test]
fn peek_does_not_remove() {
let mut stack = Stack::new();
stack.push(42);
assert_eq!(stack.peek(), Some(&42));
assert_eq!(stack.size(), 1); // still there
}
#[test]
fn empty_stack_behaviour() {
let stack: Stack<i32> = Stack::new();
assert!(stack.is_empty());
assert_eq!(stack.peek(), None);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn push_and_pop() {
let mut stack = Stack::new();
stack.push(1);
stack.push(2);
stack.push(3);
assert_eq!(stack.pop(), Some(3));
assert_eq!(stack.pop(), Some(2));
assert_eq!(stack.pop(), Some(1));
assert_eq!(stack.pop(), None);
}
#[test]
fn peek_does_not_remove() {
let mut stack = Stack::new();
stack.push(42);
assert_eq!(stack.peek(), Some(&42));
assert_eq!(stack.size(), 1); // still there
}
#[test]
fn empty_stack_behaviour() {
let stack: Stack<i32> = Stack::new();
assert!(stack.is_empty());
assert_eq!(stack.peek(), None);
}
}
The reason a stack works so naturally on top of Vec is that push and pop at the end of a contiguous array are the cheapest possible operations. No allocation per element, no pointer chasing, no cache misses from jumping across heap-allocated nodes. The CPU can predict which memory location comes next and prefetch it. This is the data locality argument that comes up constantly in Rust performance discussions: contiguous memory beats pointer-chased structures on modern hardware because CPU caches load memory in cache lines, not individual bytes, so a Vec of 64 integers loads many consecutive integers in a handful of cache line fetches while a linked list of 64 nodes requires 64 separate pointer dereferences to potentially 64 different memory locations.
The naive queue and its problem
A queue is FIFO: first in, first out. The naive implementation wraps a Vec and uses push for enqueue and remove(0) for dequeue:
<button data-code="pub struct NaiveQueue {
elements: Vec,
}
impl NaiveQueue {
pub fn new() -> Self {
NaiveQueue { elements: Vec::new() }
}
pub fn enqueue(&mut self, item: T) {
self.elements.push(item); // O(1) amortised
}
pub fn dequeue(&mut self) -> Option {
if self.elements.is_empty() {
None
} else {
Some(self.elements.remove(0)) // O(n) — this is the problem
}
}
pub fn peek(&self) -> Option {
self.elements.first()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
pub struct NaiveQueue<T> {
elements: Vec<T>,
}
impl<T> NaiveQueue<T> {
pub fn new() -> Self {
NaiveQueue { elements: Vec::new() }
}
pub fn enqueue(&mut self, item: T) {
self.elements.push(item); // O(1) amortised
}
pub fn dequeue(&mut self) -> Option<T> {
if self.elements.is_empty() {
None
} else {
Some(self.elements.remove(0)) // O(n) — this is the problem
}
}
pub fn peek(&self) -> Option<&T> {
self.elements.first()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
}
pub struct NaiveQueue<T> {
elements: Vec<T>,
}
impl<T> NaiveQueue<T> {
pub fn new() -> Self {
NaiveQueue { elements: Vec::new() }
}
pub fn enqueue(&mut self, item: T) {
self.elements.push(item); // O(1) amortised
}
pub fn dequeue(&mut self) -> Option<T> {
if self.elements.is_empty() {
None
} else {
Some(self.elements.remove(0)) // O(n) — this is the problem
}
}
pub fn peek(&self) -> Option<&T> {
self.elements.first()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
}
This compiles and passes tests. Under light load you will never notice the problem. Under heavy load, remove(0) becomes the bottleneck: removing from the front of a Vec requires shifting every remaining element one position to the left. For a queue with a million elements, each dequeue is a million-element copy. The queue gets slower as it fills up, which is exactly the wrong performance characteristic for a data structure you typically use under load.
In Java, this is the ArrayList versus LinkedList debate that every Java developer has encountered, usually after watching an ArrayList-backed queue degrade under production load. Java’s ArrayDeque exists for exactly this reason. Rust has the same solution: VecDeque.
VecDeque: the circular buffer
VecDeque is a double-ended queue backed by a circular buffer. Instead of shifting elements on every dequeue, it maintains two indices: a head pointing to the front of the queue and a tail pointing to the next insertion point. Dequeue increments head. Enqueue increments tail and wraps around when it reaches the end of the underlying allocation.
<button data-code="use std::collections::VecDeque;
pub struct Queue {
elements: VecDeque,
}
impl Queue {
pub fn new() -> Self {
Queue {
elements: VecDeque::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Queue {
elements: VecDeque::with_capacity(capacity),
}
}
pub fn enqueue(&mut self, item: T) {
self.elements.push_back(item); // O(1) amortised
}
pub fn dequeue(&mut self) -> Option {
self.elements.pop_front() // O(1) – no shifting
}
pub fn peek(&self) -> Option {
self.elements.front()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn size(&self) -> usize {
self.elements.len()
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
use std::collections::VecDeque;
pub struct Queue<T> {
elements: VecDeque<T>,
}
impl<T> Queue<T> {
pub fn new() -> Self {
Queue {
elements: VecDeque::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Queue {
elements: VecDeque::with_capacity(capacity),
}
}
pub fn enqueue(&mut self, item: T) {
self.elements.push_back(item); // O(1) amortised
}
pub fn dequeue(&mut self) -> Option<T> {
self.elements.pop_front() // O(1) - no shifting
}
pub fn peek(&self) -> Option<&T> {
self.elements.front()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn size(&self) -> usize {
self.elements.len()
}
}
use std::collections::VecDeque;
pub struct Queue<T> {
elements: VecDeque<T>,
}
impl<T> Queue<T> {
pub fn new() -> Self {
Queue {
elements: VecDeque::new(),
}
}
pub fn with_capacity(capacity: usize) -> Self {
Queue {
elements: VecDeque::with_capacity(capacity),
}
}
pub fn enqueue(&mut self, item: T) {
self.elements.push_back(item); // O(1) amortised
}
pub fn dequeue(&mut self) -> Option<T> {
self.elements.pop_front() // O(1) - no shifting
}
pub fn peek(&self) -> Option<&T> {
self.elements.front()
}
pub fn is_empty(&self) -> bool {
self.elements.is_empty()
}
pub fn size(&self) -> usize {
self.elements.len()
}
}
Both enqueue and dequeue are now O(1) amortised. The circular buffer wraps around the underlying allocation rather than shifting elements, so removing from the front costs the same as removing from the back.
The full test suite including a performance comparison that makes the difference concrete:
<button data-code="#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn enqueue_and_dequeue_ordering() {
let mut queue = Queue::new();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
assert_eq!(queue.dequeue(), Some(1)); // FIFO
assert_eq!(queue.dequeue(), Some(2));
assert_eq!(queue.dequeue(), Some(3));
assert_eq!(queue.dequeue(), None);
}
#[test]
fn peek_does_not_remove() {
let mut queue = Queue::new();
queue.enqueue(42);
assert_eq!(queue.peek(), Some(&42));
assert_eq!(queue.size(), 1);
}
#[test]
fn interleaved_enqueue_dequeue() {
let mut queue = Queue::new();
for i in 0..100 {
queue.enqueue(i);
}
for _ in 0..50 {
queue.dequeue();
}
for i in 100..150 {
queue.enqueue(i);
}
assert_eq!(queue.size(), 100);
assert_eq!(queue.peek(), Some(&50)); // first remaining element
}
#[test]
fn performance_comparison() {
let n = 10_000;
// Naive Vec-based queue
let naive_start = Instant::now();
let mut naive: Vec = Vec::new();
for i in 0..n {
naive.push(i);
}
for _ in 0..n {
naive.remove(0); // O(n) each time
}
let naive_duration = naive_start.elapsed();
// VecDeque-based queue
let vd_start = Instant::now();
let mut vd: std::collections::VecDeque = std::collections::VecDeque::new();
for i in 0..n {
vd.push_back(i);
}
for _ in 0..n {
vd.pop_front(); // O(1) each time
}
let vd_duration = vd_start.elapsed();
println!("Naive Vec queue: {:?}", naive_duration);
println!("VecDeque queue: {:?}", vd_duration);
// VecDeque should be significantly faster
assert!(vd_duration
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn enqueue_and_dequeue_ordering() {
let mut queue = Queue::new();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
assert_eq!(queue.dequeue(), Some(1)); // FIFO
assert_eq!(queue.dequeue(), Some(2));
assert_eq!(queue.dequeue(), Some(3));
assert_eq!(queue.dequeue(), None);
}
#[test]
fn peek_does_not_remove() {
let mut queue = Queue::new();
queue.enqueue(42);
assert_eq!(queue.peek(), Some(&42));
assert_eq!(queue.size(), 1);
}
#[test]
fn interleaved_enqueue_dequeue() {
let mut queue = Queue::new();
for i in 0..100 {
queue.enqueue(i);
}
for _ in 0..50 {
queue.dequeue();
}
for i in 100..150 {
queue.enqueue(i);
}
assert_eq!(queue.size(), 100);
assert_eq!(queue.peek(), Some(&50)); // first remaining element
}
#[test]
fn performance_comparison() {
let n = 10_000;
// Naive Vec-based queue
let naive_start = Instant::now();
let mut naive: Vec<i32> = Vec::new();
for i in 0..n {
naive.push(i);
}
for _ in 0..n {
naive.remove(0); // O(n) each time
}
let naive_duration = naive_start.elapsed();
// VecDeque-based queue
let vd_start = Instant::now();
let mut vd: std::collections::VecDeque<i32> = std::collections::VecDeque::new();
for i in 0..n {
vd.push_back(i);
}
for _ in 0..n {
vd.pop_front(); // O(1) each time
}
let vd_duration = vd_start.elapsed();
println!("Naive Vec queue: {:?}", naive_duration);
println!("VecDeque queue: {:?}", vd_duration);
// VecDeque should be significantly faster
assert!(vd_duration < naive_duration);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn enqueue_and_dequeue_ordering() {
let mut queue = Queue::new();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
assert_eq!(queue.dequeue(), Some(1)); // FIFO
assert_eq!(queue.dequeue(), Some(2));
assert_eq!(queue.dequeue(), Some(3));
assert_eq!(queue.dequeue(), None);
}
#[test]
fn peek_does_not_remove() {
let mut queue = Queue::new();
queue.enqueue(42);
assert_eq!(queue.peek(), Some(&42));
assert_eq!(queue.size(), 1);
}
#[test]
fn interleaved_enqueue_dequeue() {
let mut queue = Queue::new();
for i in 0..100 {
queue.enqueue(i);
}
for _ in 0..50 {
queue.dequeue();
}
for i in 100..150 {
queue.enqueue(i);
}
assert_eq!(queue.size(), 100);
assert_eq!(queue.peek(), Some(&50)); // first remaining element
}
#[test]
fn performance_comparison() {
let n = 10_000;
// Naive Vec-based queue
let naive_start = Instant::now();
let mut naive: Vec<i32> = Vec::new();
for i in 0..n {
naive.push(i);
}
for _ in 0..n {
naive.remove(0); // O(n) each time
}
let naive_duration = naive_start.elapsed();
// VecDeque-based queue
let vd_start = Instant::now();
let mut vd: std::collections::VecDeque<i32> = std::collections::VecDeque::new();
for i in 0..n {
vd.push_back(i);
}
for _ in 0..n {
vd.pop_front(); // O(1) each time
}
let vd_duration = vd_start.elapsed();
println!("Naive Vec queue: {:?}", naive_duration);
println!("VecDeque queue: {:?}", vd_duration);
// VecDeque should be significantly faster
assert!(vd_duration < naive_duration);
}
}
Building a circular buffer from scratch
Understanding what VecDeque is doing internally makes its performance characteristics obvious. A circular buffer uses a fixed-size array and two indices that wrap around:
<button data-code="pub struct CircularBuffer {
buffer: Vec<Option>,
head: usize,
tail: usize,
size: usize,
capacity: usize,
}
impl CircularBuffer {
pub fn new(capacity: usize) -> Self {
let mut buffer = Vec::with_capacity(capacity);
for _ in 0..capacity {
buffer.push(None);
}
CircularBuffer {
buffer,
head: 0,
tail: 0,
size: 0,
capacity,
}
}
pub fn push(&mut self, item: T) -> Result {
if self.size == self.capacity {
return Err("Buffer full");
}
self.buffer[self.tail] = Some(item);
self.tail = (self.tail + 1) % self.capacity; // wrap around
self.size += 1;
Ok(())
}
pub fn pop(&mut self) -> Option {
if self.size == 0 {
return None;
}
let item = self.buffer[self.head].take();
self.head = (self.head + 1) % self.capacity; // wrap around
self.size -= 1;
item
}
pub fn peek(&self) -> Option {
self.buffer[self.head].as_ref()
}
pub fn is_full(&self) -> bool {
self.size == self.capacity
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
pub struct CircularBuffer<T> {
buffer: Vec<Option<T>>,
head: usize,
tail: usize,
size: usize,
capacity: usize,
}
impl<T> CircularBuffer<T> {
pub fn new(capacity: usize) -> Self {
let mut buffer = Vec::with_capacity(capacity);
for _ in 0..capacity {
buffer.push(None);
}
CircularBuffer {
buffer,
head: 0,
tail: 0,
size: 0,
capacity,
}
}
pub fn push(&mut self, item: T) -> Result<(), &'static str> {
if self.size == self.capacity {
return Err("Buffer full");
}
self.buffer[self.tail] = Some(item);
self.tail = (self.tail + 1) % self.capacity; // wrap around
self.size += 1;
Ok(())
}
pub fn pop(&mut self) -> Option<T> {
if self.size == 0 {
return None;
}
let item = self.buffer[self.head].take();
self.head = (self.head + 1) % self.capacity; // wrap around
self.size -= 1;
item
}
pub fn peek(&self) -> Option<&T> {
self.buffer[self.head].as_ref()
}
pub fn is_full(&self) -> bool {
self.size == self.capacity
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
}
pub struct CircularBuffer<T> {
buffer: Vec<Option<T>>,
head: usize,
tail: usize,
size: usize,
capacity: usize,
}
impl<T> CircularBuffer<T> {
pub fn new(capacity: usize) -> Self {
let mut buffer = Vec::with_capacity(capacity);
for _ in 0..capacity {
buffer.push(None);
}
CircularBuffer {
buffer,
head: 0,
tail: 0,
size: 0,
capacity,
}
}
pub fn push(&mut self, item: T) -> Result<(), &'static str> {
if self.size == self.capacity {
return Err("Buffer full");
}
self.buffer[self.tail] = Some(item);
self.tail = (self.tail + 1) % self.capacity; // wrap around
self.size += 1;
Ok(())
}
pub fn pop(&mut self) -> Option<T> {
if self.size == 0 {
return None;
}
let item = self.buffer[self.head].take();
self.head = (self.head + 1) % self.capacity; // wrap around
self.size -= 1;
item
}
pub fn peek(&self) -> Option<&T> {
self.buffer[self.head].as_ref()
}
pub fn is_full(&self) -> bool {
self.size == self.capacity
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
}
The modulo operation (index + 1) % capacity is what makes it circular. When tail reaches the end of the array, it wraps back to index 0, reusing the space freed by previous pops. No element is ever shifted. No memory is reallocated. The entire operation is a single array write and an integer increment.
VecDeque does the same thing but with a growable allocation that doubles in size when full, exactly like Vec does, which is why it remains O(1) amortised rather than O(1) strictly.
The real lesson
The stack demonstrates that push and pop at the end of a Vec are already the optimal stack implementation. The queue demonstrates that the obvious extension, using Vec with removal from the front, is a correctness trap: it works but degrades quadratically under load.
In Java, you learn this lesson through ArrayDeque. In Python, through collections.deque. In Rust, the standard library makes the same recommendation through VecDeque, but the ownership model also makes the linked-list alternative more obviously painful to implement than in garbage-collected languages, which is a nudge toward the contiguous-memory solution even before you run the benchmark.
For most queue use cases in production Rust code, VecDeque is the answer. The only scenarios worth reaching for something different are bounded queues where you need backpressure, or concurrent queues where multiple threads are producing and consuming simultaneously, at which point you want crossbeam::channel or std::sync::mpsc rather than a Mutex<VecDeque<T>>.
If you are working through this series specifically to prepare for technical interviews, I have been using PracHub alongside it for mock problems and found it genuinely useful for practising the kind of scenario-based questions that come up when interviewers ask you to implement or analyse data structures under time pressure
If you want to go deeper on how Rust’s type system eliminates specific categories of these bugs at compile time, the field guide covers the ownership model, the borrow checker, and how they connect to the failures described here.
$7 — Zero to Rust: A Systems Programmer’s Field Guide
You can read the free sample here — Free 20-page sample
This is part of the Data Structures in Rust series. The linked list article covers why pointer-based structures fight Rust’s ownership model, and the binary tree article covers why hierarchical ownership works cleanly. The hash map article covers what the standard library is hiding behind HashMap’s API.

