FliegendeWurst's corner of the WWW

Using Vec::remove_item after Rust 1.51

2025-01-11

Below is a drop-in replacement for the removed Vec::remove_item, and additionally the useful function Vec::remove_all.

pub trait VecRemoveItem<T, U> {
    /// Removes the first instance of `item` from the vector if the item exists.
    fn remove_item(&mut self, item: U) -> Option<T>
    where
        U: for<'a> PartialEq<&'a T>;

    /// Removes all instance of `item` from the vector.
    fn remove_all(&mut self, item: U)
    where
        U: for<'a> PartialEq<&'a T>;
}

impl<U: for<'a> PartialEq<&'a T>, T> VecRemoveItem<T, U> for Vec<T> {
    fn remove_item(&mut self, item: U) -> Option<T> {
        self.iter().position(|n| item == n).map(|idx| self.remove(idx))
    }

    fn remove_all(&mut self, item: U) {
        self.retain(|x| item != x)
    }
}

Copying the above trait definition and adding the appropriate use statements fixes the compiler error below. You also need to remove the feature declaration.

error[E0635]: unknown feature `vec_remove_item`
 --> x.rs:1:12
  |
1 | #![feature(vec_remove_item)]
  |

error[E0599]: no method named `remove_item` found for struct `Vec<_>` in the current scope
 --> x.rs:5:4
  |
5 |     v.remove_item(&123);
  |       ^^^^^^^^^^^
  |


© FliegendeWurst, 2022-2025 (excluding evident exceptions). Website source. Contact.
This work is licensed under a Creative Commons Attribution 4.0 International License.
Website design inspired by Isabel Roses' website and Utku Demir's website.