rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
98.32k stars 12.72k forks source link

Remove first instance of item that matches predicate #57090

Open alexreg opened 5 years ago

alexreg commented 5 years ago

There is currently no method on Vec<T> to remove the first item that matches a given predicate (closure). retain can of course be used remove all items that match a predicate, and remove_item to remove the first item equal to a given value, but that's it.

What I'd like to see is something like the following method:

fn remove_pred<F, T>(&mut self, f: F) -> bool where F: FnOnce(&T) -> bool {
    if let Some(pos) = self.iter().position(f) {
        self.remove(pos);
        true
    } else {
        false
    }
}

I'm not sure if this is the most efficient way to accomplish this, however. Either way, writing the above code is not particularly ergonomic for what I envisage is a common task. (A quick Google seems to support this.)

CC @Centril (for tagging and to give feedback)

clarfonthey commented 5 years ago

Perhaps remove_matches or find_remove might be a better name.

alexreg commented 5 years ago

@clarcharr Definitely not remove_matches, because that implies more than one is removed. remove_match might work though.

TheLostLambda commented 4 months ago

An old issue, but perhaps remove_first and remove_last? Using position and rposition respectively? Might also want some swap_remove versions too? Just swap_remove_first or something? Does having a _mut version à la retain_mut make sense?

Additionally, if people have a name they like, I'd be happy to write a PR!