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