How to get the smallest and biggest values from a vector in Rust?

min max len None Option

Iterators have min and max methods that allow us to fetch the minimum and maximum values from any data that can be converted into an iterator. For example a vector.

At compile time we usually cannot know if the vector, in which we are looking for the minimum (or maximum) value has any elements. If it is empty then calling min or max will return None wrapped in an Option. We can either check the return value using match or we can prevent the call by checking the len of the vector.

examples/min-max-vector/src/main.rs

fn main() {
    let numbers: Vec<i32> = vec![23, 10, 78, 30];
    println!("numbers: {:?}", numbers);
    let min = numbers.iter().min().unwrap();
    println!("min: {}", min);

    let max = numbers.iter().max().unwrap();
    println!("max: {}", max);

    let other: Vec<i32> = vec![23];
    let empty: Vec<i32> = vec![];

    println!();
    for vec in vec![numbers, empty, other] {
        if vec.len() > 0 {
            let min = vec.iter().min().unwrap();
            println!("min: {}", min);
        } else {
            println!("empty");
        }
    }
}

numbers: [23, 10, 78, 30]
min: 10
max: 78

min: 10
empty
min: 23

Related Pages

Which value is smaller? Which is bigger? minimum and maximum in Rust
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