`VecDeque`
VecDeque<T> is a double-ended queue backed by a ring buffer. Push and pop at either end are amortised O(1), which is the operation Vec makes expensive at the front.
Detailed Explanation
Vec::insert(0, x) and Vec::remove(0) move every element. If you are building a queue — work items in the back, workers taking from the front — that cost is quadratic. VecDeque stores elements in a ring: a buffer plus a start index. Pushing on the front moves the start index backward (and wraps). No element slides.
The API mirrors both a vector and a queue. push_back / pop_back / push_front / pop_front are the ends. iter walks from front to back. Indexing dq[0] is the front. make_contiguous rotates the ring so the contents sit in one slice, which you need when an API wants &[T].
Capacity still exists. The ring grows when both ends have filled the buffer. Growth is amortised O(1) per push, same idea as Vec. with_capacity is worth calling when you know the queue depth.
VecDeque is a little heavier than Vec for purely-append workloads: an extra index, slightly more complicated iteration, and make_contiguous may copy. If you only ever push and pop at the back, Vec is the better default. If you only need a stack, Vec is the better default. VecDeque is the structure you pick because of the front.
It is not a LinkedList. It is still contiguous in one or two slices (the wrapped tail and head). Cache behaviour is close to Vec and far from node-based lists. It is not thread-safe. It is not a priority queue; that is BinaryHeap.
When you reach for VecDeque: a queue, a sliding buffer, an undo stack that also pops from the other end, BFS. When you reach for Vec: a list you append to and index. When you reach for BinaryHeap: you need the minimum or maximum, not the oldest.
Code Examples
use std::collections::VecDeque;
fn main() {
let mut q = VecDeque::new();
q.push_back("ada");
q.push_back("grace");
q.push_front("al");
println!("{:?}", q.pop_front()); // prints: Some("al")
println!("{:?}", q.pop_front()); // prints: Some("ada")
println!("{}", q[0]); // prints: grace
}Common Gotchas
`Vec` at the front is quadratic
A queue built with `insert(0)` will show up in a profiler. Change the type, not the algorithm.
`make_contiguous` may rearrange
After it returns, `dq[0]` is still the front, but the ring start is 0. Hold no pointers across that call.
Indexing a `VecDeque` is O(1) but not a single slice
`&dq[i]` is fine. A slice of the whole deque may need `make_contiguous` first.
BFS queues belong here
`push_back` the neighbours, `pop_front` the current node. A `Vec` stack is DFS.