Drain, what is it for

What is a drain method on iterator used for?

It is used to remove a range of elements from a vector, optionally giving you the elements in the range.

1 Like

Why clear couldn't be used?

Clear removes all values in the vector, but drain lets you remove only a sub-range.

let mut vec = vec![1, 2, 3, 4, 5];
println!("{:?}", vec);
[1, 5]

Additionally, the drain function returns an Iterator, which means you can see the elements as they get removed, which clear also does not let you do.

let mut vec = vec![1, 2, 3, 4, 5];
for num in vec.drain(1..=3) {
    println!("{} was removed.", num);
println!("{:?}", vec);
2 was removed.
3 was removed.
4 was removed.
[1, 5]

I don't see it mentioned much, but splice is another handy method in the same family.

You can consider drain to be a special case of splice where the input (replace_with) iterator is empty.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.