find the smallest element in an array in rust

To find the smallest element in an array in Rust, you can use the iter() method of the array to create an iterator and then call the min() method of the iterator. Here's an example:

main.rs
fn main() {
    let arr = [4, 2, 7, 1, 9, 5, 6];
    let min = *arr.iter().min().unwrap();
    println!("The smallest element in the array is {}", min);
}
155 chars
6 lines

In this example, the arr array is initialized with some random integers. We then create an iterator using the iter() method and call the min() method on it. The min() method returns an Option value that we unwrap to get the actual minimum value. Finally, we print the minimum value using the println!() macro.

Note the use of the * operator before the result of the min() method. This is necessary because min() returns a reference to the minimum element, and we need to dereference it to get the actual value.

gistlibby LogSnag