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.
vector.iter().filter(|closure_variable| closure_condition).collect();
closure_variable
: This checks the condition and iterates through the next elements of the vector via the iter()
method.
The returned iterator will yield only the elements for which the closure returns true
.
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);}
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