To remove items from a vector based on a condition in Rust, you can use the retain
method or the filter
method.
In this example,
vec
with some integer values.retain
method to remove elements that do not satisfy the specified condition. The retain
method takes a closure that returns true
for elements to keep and false
for elements to remove.fn main() {
let mut vec = vec![10, 20, 30, 40, 50];
vec.retain(|&x| x < 30);
println!("Vector after removing items based on condition: {:?}", vec);
}
Vector after removing items based on condition: [10, 20]
In this example,
vec
with some integer values.filter
method to create an iterator over the vector that yields only elements satisfying the specified condition.collect
method.fn main() {
let vec = vec![10, 20, 30, 40, 50];
let vec_new: Vec<i32> = vec.into_iter().filter(|&x| x < 30).collect();
println!("Vector after removing items based on condition: {:?}", vec_new);
}
Vector after removing items based on condition: [10, 20]
In this tutorial, we learned How to Remove Items from Vector based on a Condition in Rust language with well detailed examples.