Arrays in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

An array is a data structure that is used to contain objects of the same type T. These objects are stored in contiguous memory locations.

In Rust, the arrays are created by making the use of [ ] brackets. It is important that the size of the arrays must be known at the compile time. Also, unlike other languages like Java and C++, the length of the array is part of its type in Rust.

[T; length].

This means that an array of signature say, [i32,4], is different from an array with the signature [i32,5].

Arrays can be immutable in nature and there are many ways with which we can create such arrays.

Array without a data type

We can create arrays without providing any specific data type to it. The compiler will interpret the type on its own.

Example

 Live Demo

fn main() {
   let arr = [1,2,3];
   println!("The array is {:?}", arr);
   println!("The length of the array is: {}", arr.len());
}

Output:

The array is [1, 2, 3]
The length of the array is: 3

Array with a data type and size

We can define the data type that we want inside the array along with the size of the array, like this:

Example

 Live Demo

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

Output:

The array is [1, 2, 3, 4]
Length of the array is: 4

Default value type

If we want arrays to contain single default values, then we can do that like shown below:

Example

 Live Demo

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

Output:

The array is: [1, 1, 1, 1, 1]
Length of the array is: 5

Mutable arrays in Rust

We can also create a mutable array in Rust. Consider the example shown below:

Example

 Live Demo

fn main() {
   let mut arr:[i32;3] = [1,2,3];
   println!("Original array: {:?}",arr);
   arr[1] = 0;
   arr[2] = 100;
   println!("Changed array: {:?}",arr);
}

Output

Original array: [1, 2, 3]
Changed array: [1, 0, 100]
raja
Published on 03-Apr-2021 12:33:45
Advertisements