You can find the minimum and maximum values in a Vec using the built-in min() and max() methods, which return Option<&T> for safe handling of empty collections, or by using the minmax() method available in Rust 1.57+ to compute both in a single pass. For performance-critical code where you need both values, minmax() is preferred as it avoids iterating over the vector twice.
Here is the standard approach using min() and max() with pattern matching to handle empty vectors safely:
let numbers = vec![4, 2, 9, 1, 7];
let min_val = numbers.iter().min().copied();
let max_val = numbers.iter().max().copied();
match (min_val, max_val) {
(Some(min), Some(max)) => println!("Min: {}, Max: {}", min, max),
_ => println!("Vector is empty"),
}
If you are on Rust 1.57 or newer, use minmax() to get both values in one iteration. This returns a tuple of Option<&T>:
let numbers = vec![4, 2, 9, 1, 7];
if let Some((min, max)) = numbers.iter().minmax() {
println!("Min: {}, Max: {}", min, max);
} else {
println!("Vector is empty");
}
For mutable vectors where you need to swap elements or perform in-place operations, you can also use partial_cmp with fold, but the iterator methods above are idiomatic and efficient. If your vector contains floating-point numbers, remember that min() and max() handle NaN values by returning None if any element is NaN, so you may need to filter them out first if that behavior is undesirable.
Avoid manual loops unless you have specific custom logic, as the standard library implementations are highly optimized and readable. If you are working with large datasets and need to avoid borrowing, consider collecting the results into owned values using .copied() or .cloned() as shown in the examples.