find the last element in an array in rust

To find the last element in an array in Rust, you can use array indexing with the length of the array as the index. Here's an example:

main.rs
fn main() {
    let arr = [1, 2, 3, 4, 5];
    let last_element = arr[arr.len() - 1];
    println!("Last element: {}", last_element);
}
136 chars
6 lines

In this example, we have an array arr with 5 integers. We use arr.len() - 1 as the index to access the last element of the array. The value of last_element will be 5, which is the last element of the array.

Note that this method assumes that the array is not empty. If the array is empty, arr.len() - 1 will cause a panic. To handle this case, you can check if the array is empty before accessing the last element:

main.rs
fn main() {
    let arr = [1, 2, 3, 4, 5];
    if !arr.is_empty() {
        let last_element = arr[arr.len() - 1];
        println!("Last element: {}", last_element);
    }
}
175 chars
8 lines

This code first checks if the array is empty before accessing the last element to avoid panicking.

related categories

gistlibby LogSnag