简体   繁体   中英

How to get the minimum value of a vector in Rust?

I'm trying to display the min value of a vector in Rust and can't find a good way to do so.

Here is how I created my vector of i32 :

let mut v = vec![5, 6, 8, 4, 2, 7];

My goal here is to get the min value of that vector without having to sort it.

What is the best way to get the min value of an i32 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()

let mut v = vec![5, 6, 8, 4, 2, 7];
let minValue = *v.iter().min().unwrap();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM