octano
octano

Reputation: 991

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

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 ?

Upvotes: 69

Views: 82626

Answers (5)

Claudio Fsr
Claudio Fsr

Reputation: 434

See the functions: fn min() and fn fold().

Another option, not necessarily the most efficient.

"Folding is useful whenever you have a collection of something, and want to produce a single value from it."

fn main() {
    let values: Vec<i32> = vec![5, 6, 8, 4, 2, 7];

    // The empty vector must be filtered beforehand!
    // let values: Vec<i32> = vec![]; // Not work!!!

    // Get the minimum value without being wrapped by Option<T>
    let min_value: i32 = values
        .iter()
        //.into_iter()
        //.fold(i32::MAX, i32::min);
        .fold(i32::MAX, |arg0: i32, other: &i32| i32::min(arg0, *other));

    println!("values: {values:?}");
    println!("min_value: {min_value}");

    assert_eq!(min_value, 2);
}

See Rust Playground

Upvotes: -1

let max = nums.iter().max().unwrap_or(&0);

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

Upvotes: 0

thouger
thouger

Reputation: 435

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

Upvotes: 23

blandger
blandger

Reputation: 818

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

Upvotes: 5

Dai
Dai

Reputation: 154995

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

Upvotes: 73

Related Questions