std-method

Vec::swap_remove

Remove an element by moving the last element into its slot. This avoids shifting the suffix but may change order. An invalid index panics. Expected stdout (not executed): 20 [10, 40, 30] Common mistake: Using swap_remove where the sequence must stay ordered.

Formal Syntax & Structure

rust syntaxrust
pub fn swap_remove(&mut self, index: usize) -> T

Working Example

Example Snippetrust
fn main() {    let mut ids = vec![10, 20, 30, 40];    let removed = ids.swap_remove(1);    println!("{removed} {ids:?}");}
Rust Reference