find the length of an array in rust

To find the length of an array in Rust, you can use the .len() method. This method returns the number of elements in the array.

Here is an example code snippet:

main.rs
let arr = [1, 2, 3, 4, 5];
let length = arr.len();

println!("The length of the array is: {}", length);
104 chars
5 lines

The output of this code will be:

main.rs
The length of the array is: 5
30 chars
2 lines

In addition to .len(), you can also use the std::mem::size_of_val(&arr) function to get the total size (in bytes) of the array. And to access a specific element within the array, you can use indexing with the square brackets, as follows: arr[index]. Just be sure to use a valid index within the range of the array.

gistlibby LogSnag