To filter items of a vector based on a condition in Rust, you can use the `iter` method combined with iterator adapters like `filter` or `filter_map`.
In this example,
fn main() {
// Define a vector containing elements
let vector = vec![1, 5, 10, 15, 20];
// Specify the threshold for filtering
let threshold = 10;
// Filter items greater than the threshold
let filtered_vector: Vec<_> = vector.iter().filter(|&x| *x > threshold).cloned().collect();
// Print the filtered vector
println!("{:?}", filtered_vector);
}
[15, 20]
In this example,
fn main() {
// Define a vector containing elements
let vector = vec![1, 5, 10, 15, 20];
// Specify the condition for filtering
let condition = |&x| x % 2 == 0; // Select even numbers
// Filter items meeting the condition
let filtered_vector: Vec<_> = vector.iter().filter(|&x| condition(x)).cloned().collect();
// Print the filtered vector
println!("{:?}", filtered_vector);
}
[10, 20]
In this tutorial, we learned How to Filter Items of a Vector based on a Condition in Rust language with well detailed examples.