OneBite.Dev - Coding blog in a bite size

Find The Length Of An Array In Rust

Code snippet for how to Find The Length Of An Array In Rust with sample and detail explanation

Programming in Rust can offer a unique blend of performance and safety. One key feature commonly used is the array, and this article will explain how to simply and effectively find the length of an array in Rust.

Code snippet: Finding the length of an array in Rust

The following code snippet will show you how you can find the length of an array:

let array = [1,2,3,4,5];
let array_length = array.len();
println!("The length of the array is: {}", array_length);

Code Explanation: Finding the length of an array in Rust

Let’s break down code explanation:

  • The first line let array = [1,2,3,4,5]; declares an integer array named array with five elements in it.

  • In the second line, let array_length = array.len();, we are using the built-in method len() to find the length of the array array. This method will count the number of elements in the array and return the result. The outcome is then stored in the variable array_length.

  • The last line println!("The length of the array is: {}", array_length); then prints out the length of array to the console. We are using the print command println!, the exclamation point indicates that it’s a macro, not a function, and it produces formatted output. Inside the parentheses, the first part, "The length of the array...", is a string that gets printed as it is, and {} is a placeholder for an argument that will be stringified. In this case, the argument is array_length. When this line runs, it produces output like “The length of the array is: 5”, depending on the actual length of the array.

With these easy steps, you can find the length of any array in Rust programming language. It’s key to understand and implement these practical concepts to achieve greater proficiency in this system programming language.

rust