find the largest element in an array in rust

To find the largest element in an array in rust, you can use a function that loops through the elements of the array and keeps track of the largest element found so far. Here's an example:

main.rs
fn find_max(arr: &[i32]) -> i32 {
    let mut max = arr[0];
    for &num in arr.iter() {
        if num > max {
            max = num;
        }
    }
    max
}
161 chars
10 lines

This function takes a reference to an array of integers (&[i32]) as its argument and returns the largest element found (i32). It initializes a variable max to the first element of the array, and then loops through the rest of the elements using the iter() method of the array object.

For each element, the function checks if it is larger than the current maximum (max) and updates max accordingly. After the loop finishes, the function returns the largest element found.

You can call this function with an array like this:

main.rs
let arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
let max = find_max(&arr);
println!("The largest element is {}", max);
115 chars
4 lines

This will output:

main.rs
The largest element is 9
25 chars
2 lines

gistlibby LogSnag