What is the filter() method in Rust?

In Rust, the filter() method is used to create an iterator that determines whether or not an element should be yielded using a closure. The closure must return true or false when given an element. Only the elements for which the closure returns true will be returned in the iterator.

Syntax

vector.iter().filter(|closure_variable| closure_condition).collect();
filter() method in Rust

Parameter

  • closure_variable: This checks the condition and iterates through the next elements of the vector via the iter() method.

Return value

The returned iterator will yield only the elements for which the closure returns true.

Code example

fn main() {
// Creating a week_days vector
let week_days = vec!["Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"];
// using filter() method with days (closure with condition)
// passed as a parameter
let filtered_week_days:Vec<_> =
week_days.iter()
.filter(|days| days.len() < 8)
.collect();
println!("{:?}", filtered_week_days);
}

Explanation

  • Line 4: We create a vector named week_days.

  • Lines 15–18: In filter() method, days are passed as a closure, which checks the condition and returns the names of days whose lengths are less than eight and collect them using the collect() method and stores the result in the filtered_week_days vector.

  • Line 20: We display the result.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved