How to Filter a Vector in Rust

Filter a Rust vector by chaining .filter() with a closure and .collect() to return a new vector of matching items.

Use the .filter() method on an iterator followed by .collect() to create a new vector containing only the elements that match your condition.

fn shoes_in_size(shoes: Vec<Shoe>, shoe_size: u32) -> Vec<Shoe> {
    shoes.into_iter().filter(|s| s.size == shoe_size).collect()
}

The filter method takes a closure that returns true for items to keep, and collect gathers the results into a Vec.