VecDeque in Rust
A ring buffer: push and pop at either end in constant time.
use std::collections::VecDeque;
fn main() {
let mut queue: VecDeque<&str> = VecDeque::new();
queue.push_back("basics");
queue.push_back("errors");
queue.push_front("welcome");
println!("{:?}", queue.pop_front());
let mut window: VecDeque<i32> = VecDeque::with_capacity(3);
for n in 1..=5 {
if window.len() == 3 {
window.pop_front();
}
window.push_back(n);
}
println!("{:?}", window);
}
How it works
push_backandpop_frontmake it a queue.push_frontmakes it a deque, or an undo stack.- Popping the front before pushing keeps a fixed-size window.
Keywords and builtins used here
VecDequefnfori32ifinletmainmutstruse
The run, in numbers
- Lines
- 18
- Characters to type
- 387
- Tokens
- 126
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 84 seconds.
Step 8 of 8 in Collections, step 37 of 39 in Language basics.