Filtering a vector of custom structs in Rust involves using the iter()
method to create an iterator over the vector and then applying a
Here’s a step-by-step guide on how to filter a vector of custom structs in Rust.
We start by defining our custom struct. For this example, let’s consider a Person
struct shown below:
struct Person {id: u32name: String,age: u32,}
Next, we create a vector of our custom struct. For demonstration purposes, let’s create a vector of Person
instances:
let persons = vec![Person { id: 1, name: String::from("John"), age: 25 },Person { id: 2, name: String::from("Bob"), age: 30 },Person { id: 3, name: String::from("Alice"), age: 22 },];
filter
methodThe filter method is used to create an iterator over the elements of the vector that satisfy a predicate. In this example, we use a closure as the predicate to filter persons older than 25
as follows:
let filtered_persons: Vec<_> = persons.iter().filter(|p| p.age > 25).cloned().collect();
iter()
: It creates an iterator over the vector’s elements.
filter(|p| p.age > 25)
: It filters the elements based on the specified condition (age > 25
).
cloned()
: It clones each element to avoid moving ownership of the original vector.
collect()
: It collects the filtered elements into a new vector.
Here is a complete code example to filter a vector of custom structs in Rust:
#[derive(Debug, Clone)]struct Person {id: u32,name: String,age: u32,}fn main() {let persons = vec![Person { id: 1, name: String::from("John"), age: 25 },Person { id: 2, name: String::from("Bob"), age: 30 },Person { id: 3, name: String::from("Alice"), age: 22 },];// Filter based on a conditionlet filtered_persons: Vec<_> = persons.iter().filter(|p| p.age > 25).cloned().collect();println!("{:?}", filtered_persons);}
In Rust, filtering a vector of custom structs involves defining the struct, creating a vector of instances, and using the iter()
method along with the filter
method to apply a predicate function. In the provided example, the vector of Person
structs is filtered based on the age condition, creating a new vector containing only the desired elements. This demonstrates Rust’s expressive iterator and closure capabilities for efficient data manipulation.
Free Resources