Remove a range of items from a Vec

Viewed 967

I have a Vec in Rust with 100 items, and I need to remove every item whose index is between 10 and 30. One way to do this would be removing each element individually like so:

for i in 10..30 {
    vec.remove(i);
}

But this causes a memcpy for each removed item, because the rest of the Vec has to be shifted left every time an element is removed. How do I remove a whole range of items from a Vec in one shot, in a way that only causes one memcpy?

1 Answers

How do I remove a whole range of items from a Vec in one shot

Use Vec::drain:

vec.drain(10..30);
Related