55

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 ?

JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63
octano
  • 851
  • 1
  • 10
  • 18

4 Answers4

60
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

Dai
  • 141,631
  • 28
  • 261
  • 374
  • Thanks Dai, I think this is to get the max value, what about the min value ? Because in return I have ```Some(8)``` when I actually need to get only ```8```when I do a ```println!("{:#?}", maxValue);``` since ```println!("{}", maxValue);``` returns an error. – octano Nov 02 '19 at 09:46
  • @octano `println!("{}", maxValue.unwrap());` – tenxsoydev Oct 17 '22 at 13:14
18
let mut v = vec![5, 6, 8, 4, 2, 7];
let minValue = *v.iter().min().unwrap();
thouger
  • 385
  • 2
  • 8
  • 6
    Fairly new to Rust, but what does the * do here exactly? It works without it as well. – Callum Matthews Dec 03 '21 at 12:37
  • 1
    @CallumMatthews You can find the answer on this question, https://stackoverflow.com/questions/40531912/what-is-the-usage-of-the-asterisk-symbol-in-rust – Hercislife Apr 12 '22 at 19:41
5

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()

blandger
  • 718
  • 7
  • 17
  • @aws_apprentice When blandger replied my answer didn't include the `match` part. This was just bad timing. – Dai Nov 02 '19 at 11:51
  • There are no rules on this site for duplicate answers. You're welcome to expand your answer to attract up votes, and the key is to post correct answers. – Reactgular Nov 02 '19 at 12:19
  • Yes, the duplicate reason is timing issue, I posted answer and Dai is updated his answer soon. – blandger Nov 02 '19 at 16:37
0
let max = nums.iter().max().unwrap_or(&0);

You can use unwrap_or(value) to return default value if max not found.