How to filter a vector of custom structs in Rust

Filtering a vector of custom structs in Rust involves using the iter() method to create an iterator over the vector and then applying a predicate functionA predicate function is a function that determines whether a certain condition or predicate is true or false for a given input. to select the desired elements.

Rust vector filtering steps

Here’s a step-by-step guide on how to filter a vector of custom structs in Rust.

Step 1: Defining a custom struct

We start by defining our custom struct. For this example, let’s consider a Person struct shown below:

struct Person {
id: u32
name: String,
age: u32,
}

Step 2: Creating a vector of a custom struct

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 },
];

Step 3: Using the filter method

The 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.

Complete code

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 condition
let filtered_persons: Vec<_> = persons.iter().filter(|p| p.age > 25).cloned().collect();
println!("{:?}", filtered_persons);
}

Conclusion

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

Copyright ©2025 Educative, Inc. All rights reserved