How to Get Size of an Array Passed as an Argument

Nilesh Katuwal Feb 02, 2024
  1. Array in Rust
  2. Use the iter() Function to Fetch Values of Array Elements in Rust
How to Get Size of an Array Passed as an Argument

This article is about arrays and getting the size of an array passed in as an argument in Rust.

Array in Rust

An array is known as the homogeneous collection of different values. We can also say that an array is the collection of values having the same data type.

Sequential memory blocks are allocated once the array is declared. They cannot be resized once initialized as they are static.

Each memory block represents an array element. The values of an array element can be updated or modified, but they cannot be deleted.

An example of one simple array is written below.

fn main(){
   let arr:[i32;5] = [11,12,13,14,15];
   println!("Array is {:?}",arr);
   println!("The size of the array is: {}",arr.len());
}

Output:

Array is [11, 12, 13, 14, 15]
The size of the array is: 5

The following example code creates the array, and all its elements are initialized with the default value of -1.

fn main() {
   let arr:[i32;4] = [-1;4];
   println!("The array is {:?}",arr);
   println!("The size of the array is: {}",arr.len());
}

Output:

The array is [-1, -1, -1, -1]
The size of the array is: 4

Use the iter() Function to Fetch Values of Array Elements in Rust

The iter() function is used to fetch the values of all elements available in an array.

Example Code:

fn main(){

let num:[i32;4] = [50,60,70,80];
   println!("The array is {:?}",num);
   println!("The size of the array is: {}",num.len());

   for val in num.iter(){
      println!("The value of the array is: {}",val);
   }
}

Output:

The array is [50, 60, 70, 80]
The size of the array is: 4
The value of the array is: 50
The value of the array is: 60
The value of the array is: 70
The value of the array is: 80

Related Article - Rust Array