Rust VecDeque
A VecDeque is a double-ended queue that is fast at both ends. Items can join or leave at the front or the back.
Add to both ends
push_back joins the back of the line. push_front cuts to the front.
use std::collections::VecDeque;
let mut line: VecDeque<&str> = VecDeque::new();
line.push_back("Ana");
line.push_back("Bo");
line.push_front("Zoe");
println!("{:?}", line);Serve from the front (a queue)
pop_front takes the next person in line — first in, first out.
println!("{:?}", line.pop_front());Take from the back (a stack)
pop_back takes the last arrival instead — the same value also works as a stack.
println!("{:?}", line.pop_back());Look at both ends
front() and back() peek without removing anything.
println!("{:?}", line.front());
println!("{:?}", line.back());Example
use std::collections::VecDeque;
fn main() {
let mut line: VecDeque<&str> = VecDeque::new();
line.push_back("Ana");
line.push_back("Bo");
println!("serving: {:?}", line.pop_front());
line.push_back("Cy");
line.push_back("Di");
println!("serving: {:?}", line.pop_front());
println!("still waiting: {:?}", line);
println!("next up: {:?}", line.front());
}Key points
- VecDeque lives in std::collections::VecDeque.
- A queue is first in, first out.
- Use push_back to join and pop_front to be served.
- Both stay fast.
- Vec::remove(0) does not, because it shifts every item.
- pop_front and pop_back return Option — None when the deque is empty.
- Indexing and iteration work exactly like a Vec: line[0] and for person in &line.
Ana and Bo join. Ana is served from the front. Cy and Di join the back. Bo is served. The two left are exactly the last two arrivals in order. Serving is pop_front: the oldest arrival leaves first, which is what makes it a queue.
Note
Pick Vec for most lists — it is simpler and scans faster.
Reach for VecDeque when items regularly join or leave at the front.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
A print shop serves jobs in arrival order. Which call takes the next job?