HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howwithinthevectorrustvalueminimumget

Problem

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 in Rust ?

Solution

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

Code Snippets

let minValue = vec.iter().min();
match minValue {
    Some(min) => println!( "Min value: {}", min ),
    None      => println!( "Vector is empty" ),
}
fn min(self) -> Option<Self::Item>
where
    Self::Item: Ord,

Context

Stack Overflow Q#58669865, score: 76

Revisions (0)

No revisions yet.