HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfromremovetheelementvectorgiven

Problem

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

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

Context

Stack Overflow Q#26243025, score: 130

Revisions (0)

No revisions yet.