OneBite.Dev - Coding blog in a bite size

Find The Minimum And Maximum Element In An Array In Rust

Code snippet for how to Find The Minimum And Maximum Element In An Array In Rust with sample and detail explanation

Finding the minimum and maximum element in an array is a common task in various areas of computer programming. This article will guide you through the necessary steps to perform this operation in Rust, a popular, memory-efficient language with a strong performance focus.

Code Snippet: Finding Minimum and Maximum Element in an Array

fn main() {
    let numbers = [8, 3, 2, 4, 9, 1, 5];
    let min = *numbers.iter().min().unwrap();
    let max = *numbers.iter().max().unwrap();

    println!("The minimum number is {}", min);
    println!("The maximum number is {}", max);
}

Code Explanation for Finding Minimum and Maximum Element in an Array

The first step of this code snippet is function declaration. We start with fn main() {, which declares the main function. This is where our program will start to execute.

The next line, let numbers = [8, 3, 2, 4, 9, 1, 5];, declares an array of integers named numbers. This array holds the elements we are going to identify the min and max values from.

Following this, let min = *numbers.iter().min().unwrap(); finds the minimum number from our array. Here’s what happens in this line:

  • numbers.iter() creates an iterator over the numbers array.
  • .min() finds the minimum element in the array and returns an Option.
  • The unwrap method is then used to extract the value from the Option returned by min(). This method returns the content of an Ok, or panics if it is an Err.

Similar to finding the minimum number, let max = *numbers.iter().max().unwrap(); finds the maximum number from our array. The steps to do this are identical to finding the minimum number, but we use the .max() function instead of .min().

Finally, println!() functions are used to display the minimum and maximum numbers on the console. The {} brackets are placeholders which the println!() function will replace with the values of min and max respectively.

This concludes the step-by-step walkthrough of the code. By following these steps, we can easily find the minimum and maximum elements in any array in Rust.

rust