Home:ALL Converter>How to get the minimum value within a vector in Rust?

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

Ask Time:2019-11-02T17:39:38         Author:octano

Json Formatter

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

Given a vector of i32 :

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

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

What is the best way to get the minimum value within a Vec<i32> in Rust ?

Author:octano,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58669865/how-to-get-the-minimum-value-within-a-vector-in-rust
Dai :

let minValue = vec.iter().min();\nmatch minValue {\n Some(min) => println!( \"Min value: {}\", min ),\n None => println!( \"Vector is empty\" ),\n}\n\n\nhttps://doc.rust-lang.org/std/iter/trait.Iterator.html#method.min\n\n\nfn min(self) -> Option<Self::Item>\nwhere\n Self::Item: Ord, \n\n \n Returns the minimum element of an iterator.\n \n If several elements are equally minimum, the first element is returned. If the iterator is empty, None is returned.\n\n\nI 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",
2019-11-02T09:42:51
thouger :

let mut v = vec![5, 6, 8, 4, 2, 7];\nlet minValue = *v.iter().min().unwrap();\n",
2021-03-09T15:29:56
yy