Vec

Vec indexing versus get, push and pop, and the difference between remove and swap_remove.

Vec<T> is the standard-library growable array type, not a module and not a third-party collection crate. It is included in the prelude, so you can write Vec and vec! without importing them. A Vec owns its elements. Methods that take &self borrow the vector; methods that take &mut self, such as push, remove, and swap_remove, need exclusive access.

This page documents indexing, get, and the two ways to remove an element. It does not cover every adapter on slices or every drain helper.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Vec indexing, Vec::get, Vec::push, Vec::popRead an element by position. Indexing panics on an out-of-range index; get returns None. push and pop grow and shrink the vector in place.
Vec::remove, Vec::swap_removeTake one element out of a vector. remove keeps the order of the rest; swap_remove is faster and does not keep that order.

Indexing versus get

v[i] uses the Index trait and returns a reference to the element, or panics if i is out of bounds. v.get(i) returns Option<&T> and yields None when the index is missing. Use get when the index comes from untrusted input; use indexing when a missing element would be a programming error.

Vec indexing, Vec::get, Vec::push, Vec::pop

fn get(&self, index: usize) -> Option<&T>
fn push(&mut self, value: T)
fn pop(&mut self) -> Option<T>
// v[index] via Index, panics when out of bounds

Read an element by position. Indexing panics on an out-of-range index; get returns None. push and pop grow and shrink the vector in place.

ParameterDescription
indexA zero-based position. It is not a byte offset, even when T is u8.
valueThe element to append. push takes ownership of value.

Returns: get returns Option<&T> borrowed from the vector. pop returns Option<T> and transfers ownership of the last element. Indexing returns &T, or panics.

Errors and panics

  • panic — v[index] panics when index >= v.len(). get and pop do not panic for an empty or short vector; they return None.
  • Holding a reference from get or from v[i] borrows the vector. You cannot push while that reference is still in use.
  • The panic hook in this example is cleared so the failed index can be reported as a boolean without writing a backtrace to stderr.
rust
fn main() {
    let mut values = vec![10, 20, 30];
    println!("index1={}", values[1]);
    println!("get1={:?} get9={:?}", values.get(1), values.get(9));
    std::panic::set_hook(Box::new(|_| {}));
    let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = values[9];
    }))
    .is_err();
    println!("index9 panicked={panicked}");
    values.push(40);
    println!("pop={:?} now={:?}", values.pop(), values);
}

Expected output

index1=20
get1=Some(20) get9=None
index9 panicked=true
pop=Some(40) now=[10, 20, 30]

Related: Vec::get

Official documentation →

remove and swap_remove

remove(i) takes the element at i and shifts everything after it to the left, so the relative order of the remaining elements is preserved. That shift is O(n). swap_remove(i) replaces the removed element with the last element, which is O(1), but it changes the order of the tail.

Both methods panic if the index is out of bounds, and both return the removed element by value.

Vec::remove, Vec::swap_remove

fn remove(&mut self, index: usize) -> T
fn swap_remove(&mut self, index: usize) -> T

Take one element out of a vector. remove keeps the order of the rest; swap_remove is faster and does not keep that order.

ParameterDescription
indexThe position of the element to take. Both methods panic when index >= len.

Returns: The removed element, moved out of the vector. The vector is shortened by one.

Errors and panics

  • panic — Both methods panic if the index is out of bounds. There is no Option-returning variant of these two methods.
  • After remove(1) on ["a", "b", "c", "d"], the vector is ["a", "c", "d"].
  • After swap_remove(1) on the same input, the vector is ["a", "d", "c"]. The last element fills the hole.
  • If you need a removal that returns Option, check the index first or use a different structure.
rust
fn main() {
    let mut kept = vec!["a", "b", "c", "d"];
    let removed = kept.remove(1);
    println!("remove={removed} after={kept:?}");

    let mut swapped = vec!["a", "b", "c", "d"];
    let taken = swapped.swap_remove(1);
    println!("swap_remove={taken} after={swapped:?}");
}

Expected output

remove=b after=["a", "c", "d"]
swap_remove=b after=["a", "d", "c"]

Related: Vec::remove, Vec::swap_remove

Official documentation →