OneBite.Dev - Coding blog in a bite size

Get The Nth Element Of Array In Rust

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

If you’re delving into Rust programming language, you might be curious about how to get the Nth element of an array in Rust. This guide will show you how you can do it, with an example code snippet and a step-by-step explanation of how the code works.

Code snippet to get the Nth element of an array in Rust:

fn main() {
    let array = [10, 20, 30, 40, 50];
    let index = 2;
    println!("The element at index {} is {}.", index, array[index]);
}

Code Explanation for getting the Nth element of an array in Rust:

  1. First thing to do is to define our function main(). This function is the entry point of our Rust program.
fn main() {
  1. Next, we declare our array. In this example, we’re using a simple array of integers with five elements: 10, 20, 30, 40, 50.
let array = [10, 20, 30, 40, 50];
  1. We then need to specify the index of the element we want to access. Remember, in most programming languages, array indices start at 0. So if we want the third element of the array, our index will be 2.
let index = 2;
  1. Now that we have our array and our index, we can print the Nth element. We’ll use Rust’s println! macro to do this. The placeholders {} will get replaced by the subsequent arguments - index and array[index].
println!("The element at index {} is {}.", index, array[index]);
  1. Finally, we close our function.
}

You can try running this code. It should correctly print: “The element at index 2 is 30.”, because the element at index 2 in the array [10, 20, 30, 40, 50] is indeed 30.

And that’s it! Now, you know how to get the Nth element of an array in Rust. It’s as simple as specifying the index of the element you want after the name of the array, just like in many other programming languages.

rust