Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Queue

  • VecDeque

  • push_back

  • pop_front

  • len

  • capacity

  • VecDeque provides for a fast queue

  • It probably has to be mutable to make sense though we could create one from a fixed list of values and then just access the elements.

  • We can add element at the end using push_back.

  • We can fetch elements from the front using pop_front.

  • As we add more elements Rust will automatically grow the capacity of the vector by a little bit more than needed to allow for faster growth.

use std::collections::VecDeque;

fn main() {
    let mut doctor = VecDeque::new();
    println!(
        "len: {} capacity: {} empty:  {}",
        doctor.len(),
        doctor.capacity(),
        doctor.is_empty()
    );

    doctor.push_back(String::from("cat"));
    println!(
        "len: {} capacity: {} empty:  {}",
        doctor.len(),
        doctor.capacity(),
        doctor.is_empty()
    );

    doctor.push_back(String::from("dog"));
    doctor.push_back(String::from("rat"));
    doctor.push_back(String::from("squirrel"));
    doctor.push_back(String::from("snake"));
    println!(
        "len: {} capacity: {} empty:  {}",
        doctor.len(),
        doctor.capacity(),
        doctor.is_empty()
    );

    println!("{:?}", doctor); // I can print the whole queue, but there is probably no point for that

    let next = doctor.pop_front();
    println!("{}", next.unwrap());
    println!(
        "len: {} capacity: {} empty:  {}",
        doctor.len(),
        doctor.capacity(),
        doctor.is_empty()
    );
}
len: 0 capacity: 0 empty:  true
len: 1 capacity: 4 empty:  false
len: 5 capacity: 8 empty:  false
["cat", "dog", "rat", "squirrel", "snake"]
cat
len: 4 capacity: 8 empty:  false