Rust filter
Created By: chatGPT
Rust provides powerful tools for filtering collections. The most common way to filter data in Rust is through the use of iterators and the
In the above example, we have a vector called filter
method. This allows you to specify a condition that each element must meet to be included in the resulting collection. Below, we will explore how to filter a vector of integers to include only even numbers.fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6];
let even_numbers: Vec<i32> = numbers.iter()
.filter(|&&x| x % 2 == 0)
.cloned()
.collect();
println!("Even numbers: {:?}", even_numbers);
}
numbers
containing integers from 1 to 6. The filter
method is called on the iterator produced by numbers.iter()
. We use a closure |&&x| x % 2 == 0
to check if a number is even. The closure takes a reference to an integer and checks if it's divisible by 2. The cloned()
method is used to convert the iterator of references back into values, and collect()
gathers the results into a new vector.You can also filter more complex structures. For instance, if you have a struct representing a person, you might filter based on their age. Here is a quick example of filtering a list of
Person
structs to find all individuals of a certain age or older.#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
fn main() {
let people = vec![
Person { name: String::from("Alice"), age: 30 },
Person { name: String::from("Bob"), age: 25 },
Person { name: String::from("Eve"), age: 35 },
];
let older_than_28: Vec<&Person> = people.iter()
.filter(|&&p| p.age >= 28)
.collect();
for person in older_than_28 {
println!("{} is {} years old.", person.name, person.age);
}
}