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();
Parameter
closure_variable: This checks the condition and iterates through the next elements of the vector via theiter()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 vectorlet week_days = vec!["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];// using filter() method with days (closure with condition)// passed as a parameterlet 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 thecollect()method and stores the result in thefiltered_week_daysvector.Line 20: We display the result.
Free Resources