rust

How to remove an element from a vector given the element?


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

  • 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()).