typestar

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

  1. push_back and pop_front make it a queue.
  2. push_front makes it a deque, or an undo stack.
  3. Popping the front before pushing keeps a fixed-size window.

Keywords and builtins used here

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.

Type this snippet

Step 8 of 8 in Collections, step 37 of 39 in Language basics.

← Previous Next →