Vec retain give an &T but could expose a &mut T

Hey,

I found out that the Vec::retain method is way better to use than a bunch of Vec::remove when you need to potentially remove more than one element in one roll.

Still, I also discover that this function only gives an immutable reference to the elements inside. That's sad because it can give a mutable one and allow a more thorough set of use cases to be done with that function.

Changing the function signature (the argument of the retain method) is a breaking change. I tried to change it in the std, and BinaryHeap wasn't happy about that. So I would like your advice, is it better to create a new Vec::retain_mut or just let users implement their own function to do that?

// implemented on Vec<T>
fn retain_mut<F>(&mut self, mut f: F) where F: FnMut(&mut T) -> bool;

While retain_mut sounds ok to me, there's also drain_filter that does give you &mut T, and you can just drop/ignore the returned iterator to discard those items.

2 Likes

This forum is about using Rust. If you want to propose changes and ask about feedback, then the internals forum is the place to go.

2 Likes

Ho, thanks, it does seem that this function is akin to the retain method, but with the mutable reference available.

There's some difference in panic behavior though, since draining has to deal with the fact that some of the items may have been moved out. Retain just ends up with shuffled items if you panic, which is still safe. If you never panic, then drain_filter/retain_mut semantics would be the same, but with possibly pessimized performance in drain for those checks.

1 Like