Filter vector of numbers in Rust

filter collect

Using a range to create a vector of numbers.

Using filter to create lists of selected numbers.

We had two dereference the numbers to be able to compare them.

examples/filter-vector-of-numbers/src/main.rs


fn main() {
    let numbers = (1..100).collect::<Vec<u32>>();
    println!("total: {}", numbers.len());

    let small = numbers.iter().filter(|num| **num < 10).collect::<Vec<_>>();
    println!("small: {}", small.len());

    let big = numbers.iter().filter(|num| **num > 80).collect::<Vec<_>>();
    println!("big:   {}", big.len());

    let odd = numbers.iter().filter(|num| *num % 2 == 1).collect::<Vec<_>>();
    println!("odd:   {}", odd.len());
    println!("odd:   {:?}", odd);
}

Related Pages

Vectors in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo