VecDeque
With the VecDeque
in Rust, part of the std collections, we have a ring buffer. The front and back of the VecDeque
can be added to or removed from with good performance.
Based on a Vector
, the VecDeque
helps us maintain the buffer's elements. To add elements, we use push_back
or push_front
. To remove elements, we use pop_back
or pop_front
.
This program uses the Rust VecDeque
in a variety of ways. It adds to the end and start with push_back
and push_front
, then loops over the elements.
VecDeque
with the new()
method. We call push_back
3 times and add integers to the buffer.for
-loop to iterate over the elements stored within the VecDeque
.with_capacity
to create a VecDeque
. Here we also use push_front
to add to the buffer's start.front()
and back()
. These return Options, so we can access them in a if-let
statement.clone()
the VecDeque
. We can also convert it to a Vec
with the collect method.pop_back
and pop_front
. We can even rotate elements left and right.use std::collections::*; fn main() { // Part 1: create VecDeque and add 3 elements to it with push_back. let mut v = VecDeque::new(); v.push_back(100); v.push_back(200); v.push_back(300); // Part 2: loop over VecDeque. for element in v { println!("Element: {element}"); } // Part 3: create VecDeque with a starting capacity, and use push_front. let mut x = VecDeque::with_capacity(10); x.push_back("my"); x.push_back("friend"); x.push_back("!"); x.push_front("hello"); // Part 4: access front and back of VecDeque. if let Some(front) = x.front() { if let Some(back) = x.back() { println!("front = {}; back = {}", front, back); } } // Part 5: clone and convert into a Vec. let result = x.clone().into_iter().collect::<Vec<&str>>(); println!("clone {:?}", result); // Part 6: pop_back and rotate_left. x.pop_back(); println!("pop_back {:?}", x); x.rotate_left(1); println!("rotate_left {:?}", x); }Element: 100 Element: 200 Element: 300 front = hello; back = ! clone ["hello", "my", "friend", "!"] pop_back ["hello", "my", "friend"] rotate_left ["my", "friend", "hello"]
As it uses a Vector
internally, the VecDeque
could be replaced with a Vector
. But by using the pre-built VecDeque
helper methods, our programs are shorter and easier to maintain.