Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Collections

Rust Vec insert, remove and swap_remove

Reference for Vec::insert, remove, swap_remove and replace in Rust: shifting cost, panics on bad indexes, order-preserving versus O(1) removal.

insert(index, value) puts an element at a position and shifts everything after it one slot to the right. remove(index) takes an element out and shifts the tail left to close the gap, returning the removed value. Both keep the order of the remaining elements and cost O(n) in the worst case.

swap_remove(index) is the fast alternative: it removes an element by moving the last element into its place. That is O(1), but the order changes. Pick it when a vector is really a bag of items.

Rust
let mut v = vec![10, 20, 30];
v.insert(1, 15);       // [10, 15, 20, 30]
let gone = v.remove(0); // 10

Try it

Rust Insert and remove

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Out-of-range indexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl<T> Vec<T> {
    pub fn insert(&mut self, index: usize, element: T);
    pub fn remove(&mut self, index: usize) -> T;
    pub fn swap_remove(&mut self, index: usize) -> T;
}
Name Description
index Position to insert at or remove from. For insert it may equal len(); for the removers it must be less than len().
element The value to insert, moved into the vector.

Returns: insert returns nothing. remove and swap_remove return the removed element by value.

Panics: insert panics when index > len. remove and swap_remove panic when index >= len. The message states both numbers.

Usage notes

  • Cost: insert and remove move len - index elements, so removing from the front of a large vector repeatedly is quadratic. Use VecDeque for front operations, or drain to remove many items in one pass.
  • swap_remove changes order. If you must keep order, use remove. If you need to delete the last element, pop is cleaner.
  • Inserting may reallocate when len == capacity. Insertion into the middle never keeps old references valid, which the borrow checker enforces.
  • Removing while iterating does not compile if you iterate by reference. Collect indexes first, use retain, or loop backwards over indexes.
  • Take, don't clone. remove hands you ownership, so no clone is needed to move a String out of a vector. std::mem::take(&mut v[i]) leaves a default value behind without shifting anything.
  • Replace in place: assign with v[i] = new (drops the old value) or use std::mem::replace to get the old value back.
  • Related slice methods: swap(a, b) exchanges two positions, and rotate_left moves a block (see swap, reverse, rotate).
  • Vec::remove returns T, not Option<T>. Contrast with HashMap::remove, which returns an Option.