Remove an element from a vector

Is there a simple way to remove an element from a Vec<T>?

There's a method called remove(), and it takes an index: usize, but there isn't even an index_of() method that I can see.

I'm looking for something (hopefully) simple and O(n).


Solution 1:

This is what I have come up so far (that also makes the borrow checker happy):

let index = xs.iter().position(|x| *x == some_x).unwrap();
xs.remove(index);

I'm still waiting to find a better way to do this as this is pretty ugly.

Note: my code assumes the element does exist (hence the .unwrap()).

Solution 2:

You can use the retain method but it will delete every instance of the value:

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