How to get the minimum value of a vector in Rust?
let minValue = vec.iter().min();
match minValue {
Some(min) => println!( "Min value: {}", min ),
None => println!( "Vector is empty" ),
}
https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min
fn min(self) -> Option<Self::Item> where Self::Item: Ord,
Returns the minimum element of an iterator.
If several elements are equally minimum, the first element is returned. If the iterator is empty, None is returned.
I found this Gist which has some common C#/.NET Linq operations expressed in Swift and Rust, which is handy: https://gist.github.com/leonardo-m/6e9315a57fe9caa893472c2935e9d589
Hi @octano As Dai has already answered, min/max return Option<> value, so you can only match it as in example:
fn main() {
let vec_to_check = vec![5, 6, 8, 4, 2, 7];
let min_value = vec_to_check.iter().min();
match min_value {
None => println!("Min value was not found"),
Some(i) => println!("Min Value = {}", i)
}
}
Play ground example for Iter.min()