How to Remove an Element from a Vector in Rust

Created
Modified

Using retain Function

The vec::retain() function retains only the elements specified by the predicate.

For example,

fn main() {
  let mut v = vec![1, 3, 2, 3, 4];
  v.retain(|&x| x != 3);
  println!("{:?}", v);
}
[1, 2, 4]

Using remove Function

The vec::remove() function removes and returns the element at position index within the vector, shifting all elements after it to the left.

See the following example:

fn main() {
  let mut v = vec![1, 3, 2, 3, 4];

  // Remove first element
  if let Some(pos) = v.iter().position(|x| *x == 3) {
    v.remove(pos);
  }
  println!("{:?}", v);

  // Remove last element
  v = vec![1, 3, 2, 3, 4];
  if let Some(pos) = v.iter().rposition(|x| *x == 3) {
    v.remove(pos);
  }
  println!("{:?}", v);
}
[1, 2, 3, 4]
[1, 3, 2, 4]

Rust Errors

None:

let i = v.iter().position(|x| *x == 5).unwrap();
thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:3:42

cannot borrow as mutable:

let v = vec![1, 3, 2, 3, 4];
 --> src/main.rs:4:3
  |
2 |   let v = vec![1, 3, 2, 3, 4];
  |       - help: consider changing this to be mutable: `mut v`
3 |   let i = v.iter().position(|x| *x == 5).unwrap();
4 |   v.remove(i);
  |   ^^^^^^^^^^^ cannot borrow as mutable

Related Tags