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

Stack and the capacity of a vector

  • push
  • pop
  • len
  • capacity

A little example showing how a vector growth its length (len) and capacity as we push more and more values on it.

Then how it reduces the length but keeps the allocated capacity as we pop out elements.

Finally how it can reduce the capacity when calling shrink_to_fit.

fn main() {
    let mut stack = vec![];
    show(&stack);

    stack.push(String::from("dog"));
    show(&stack);

    stack.push(String::from("snake"));
    show(&stack);

    stack.push(String::from("cat"));
    show(&stack);

    stack.push(String::from("turle"));
    show(&stack);

    stack.push(String::from("camel"));
    show(&stack);

    stack.pop();
    show(&stack);

    stack.pop();
    show(&stack);

    stack.shrink_to_fit();
    show(&stack);
}

fn show(stack: &Vec<String>) {
    println!("{}, {}, {:?}", stack.len(), stack.capacity(), stack);
}
0, 0, []
1, 4, ["dog"]
2, 4, ["dog", "snake"]
3, 4, ["dog", "snake", "cat"]
4, 4, ["dog", "snake", "cat", "turle"]
5, 8, ["dog", "snake", "cat", "turle", "camel"]
4, 8, ["dog", "snake", "cat", "turle"]
3, 8, ["dog", "snake", "cat"]
3, 3, ["dog", "snake", "cat"]