OneBite.Dev - Coding blog in a bite size

Count Array's Length In Rust

Code snippet for how to Count Array's Length In Rust with sample and detail explanation

Rust is a highly efficient language aimed towards system and web development. Knowing how to count an Array’s length in Rust is a fundamental part of understanding and using the language effectively.

Code snippet for Counting an Array’s Length in Rust

Here’s a simple and straightforward code snippet to count the array’s length in Rust:

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

    println!("The length of the array is: {}", lenght_of_numbers);
}

This code introduces an array named “numbers” and prints the length of this array.

Code Explanation for Counting an Array’s Length in Rust

Let’s break down the Rust code to understand its working in a better way:

  1. Here’s the main function where our code resides:
fn main() {}
  1. Inside the main function, we introduced an array named “numbers”:
let numbers = [1, 2, 3, 4, 5];

In this case, our array comprises five elements.

  1. Then we’re using the .len() method that returns us the length of the array:
let lenght_of_numbers = numbers.len();

This line assigns the length of the array (which is 5) to the variable “lenght_of_numbers”.

  1. Finally, we’re making a call to the println! macro to print the length of our array:
println!("The length of the array is: {}", lenght_of_numbers);

In this line, {} is a placeholder for the value of “lenght_of_numbers”. It gets replaced by the length of the array when the program runs, and hence, outputs: “The length of the array is: 5”

So, using the .len() method, you can effectively count the length of an array in Rust. This method is simple to use, efficient and produces fast results which are the main objectives of the Rust language.

rust