To remove a specific item from a vector in Rust, you can use the retain
method or the iter().filter()
method.
In this example,
vec
with some integer values.item_to_remove
.retain
method to remove the specified item. The retain
method takes a closure that determines which elements to keep; elements for which the closure returns false
are removed.item_to_remove
and return true
only if the element is not equal to item_to_remove
.fn main() {
let mut vec = vec![10, 20, 30, 40, 50];
let item_to_remove = 30;
vec.retain(|&x| x != item_to_remove);
println!("Vector after removing the item {}: {:?}", item_to_remove, vec);
}
Vector after removing the item 30: [10, 20, 40, 50]
In this example,
vec
with some integer values.item_to_remove
.iter()
method to create an iterator over the vector.filter
method to create a new iterator that only includes elements not equal to item_to_remove
. The filter
method takes a closure that returns true
for elements to keep and false
for elements to exclude.collect
method.fn main() {
let vec = vec![10, 20, 30, 40, 50];
let item_to_remove = 30;
let vec_new: Vec<i32> = vec.iter().filter(|&&x| x != item_to_remove).cloned().collect();
println!("Vector after removing the item {}: {:?}", item_to_remove, vec_new);
}
Vector after removing the item 30: [10, 20, 40, 50]
In this tutorial, we learned How to Remove Specific Item from a Vector in Rust language with well detailed examples.