OneBite.Dev - Coding blog in a bite size

Get The Last Element Of Array In Rust

Code snippet for how to Get The Last Element Of Array In Rust with sample and detail explanation

Diving deep into the world of programming with Rust often involves manipulating and understanding arrays. This article is specifically going to explore how you can get the last element of an array in Rust.

Code snippet for fetching the last element of an array

For instruction purposes, let’s initialize an array with some numbers.

fn main() {
    let numbers = [1,2,3,4,5];
    let last_number = numbers.last();

    match last_number {
        Some(last_number) => println!("The last number is {}", last_number),
        None => println!("The array is empty"),
    }
}

Code Explanation for fetching the last element of an array

The program starts with the function main() where all Rust programs begin execution.

The first line inside main() is the array declaration. Here we declare an array numbers and assign it with some integers ([1,2,3,4,5]).

In the second line, we use the .last() method in Rust. This method is called on our numbers array to get the last element. The .last() method returns an option that can either be Some if there’s a value, or None if the array is empty.

Next, to output the value, we use Rust’s match expression. The match expression is used for pattern matching in Rust.
Here it checks the last_number Option returned by the .last() method. If it is Some(number), that is - if the number is available, it will print the statement “The last number is {}”, with the value of the last number. If it’s None, which happens when the array is empty, it will print “The array is empty”.

This is a simple example of how you can get the last element of an array in Rust. It’s a very common operation and knowing how to perform it is an essential part of mastering Rust.

rust