CodeBlanks Logo Icon CodeBlanks

Push and pop

Add and remove elements with push and pop.

Adding and removing

Methods that change the vector need a mut variable:

let mut v = vec![1, 2];
v.push(3);            // add to the end: [1, 2, 3]
v.insert(0, 0);       // add at position 0: [0, 1, 2, 3]
let son = v.pop();    // Some(3): [0, 1, 2]
let ilk = v.remove(0);// 0: [1, 2]

pop is safe on an empty vector too (it returns None), because the result is an Option<T>. remove and insert panic on an invalid index.

Bulk operations

To add or remove several elements at once:

let mut v = vec![1, 2];
v.extend([3, 4, 5]);        // [1, 2, 3, 4, 5]
v.truncate(3);              // [1, 2, 3]
let kalan: Vec<i32> = v.drain(1..).collect();   // v = [1], kalan = [2, 3]
v.clear();                  // []

swap_remove(i) replaces the element with the last one and removes it; the order breaks but it's O(1).

Practice Add and remove

Start with let mut v = vec![1, 2];. Apply push(3), insert(0, 0), let son = v.pop(); and let ilk = v.remove(0); in order. Print v, son ({:?}) and ilk on one line.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let mut v = vec![1, 2];
    v.push(3);
    v.insert(0, 0);
    let son = v.pop();
    let ilk = v.remove(0);
    println!("{:?} {:?} {}", v, son, ilk);
}

Expected output

[1, 2] Some(3) 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the performance difference between <code>insert(0, x)</code> and <code>push(x)</code>?

  • insert doesn't allocate
  • insert(0, ..) shifts every element (O(n)); push is usually O(1) Correct answer
  • There is no difference
  • push is slower

Explanation: If you often add to the front, VecDeque is a better fit.

2 Pull from the end

Question
let mut v = vec![1, 2, 3];
let son = v.____();   // Some(3)
Answer
let mut v = vec![1, 2, 3];
let son = v.pop();   // Some(3)

Explanation: pop removes the last element and returns it inside an Option.

3 Method and effect on [1, 2, 3]

Term Meaning
push(4) [1, 2, 3, 4]
pop() Some(3)
remove(0) Returns 1
insert(1, 9) [1, 9, 2, 3]

All lessons in Beginner