Concept of Mutable Array

To declare the mutable array we use “mut” key. Mutable arrays are those arrays whose elements can be altered. See the example below for a better understanding.

Rust




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


Output:

[1, 0, 3, 4, 5]

We have updated the value of the array at index number “1” and print the value.

Rust – Array

An Array in Rust programming is a fixed-sized collection of elements denoted by [T; N] where T is the element type and N is the compile-time constant size of the array.

We can create an array in 2 different ways:

  1. Simply a list with each element [a, b, c].
  2. Repeat expression [N, X].  This will create an array with N copies of X.

[X,0] It is allowed but can cause some hectic problems so if you are using this type of expression be mindful of side effects. Array size from 0-32 implements the default trait if allowed by its type. Trait implementations are up to 32 sizes. An array is not iterateable itself.

Syntax:

ArrayType : [ Type ; Expression]

An array is written as:

let array: [i32; 3] = [4, 5, 6];

Similar Reads

Features of an Array

Memory blocks in the array are in sequential order. Once an array is created it cannot be resized which means the array is static. The array element is represented by the memory block To identify array elements we use a unique integer known as a subscript. Putting values in the array element is known as array initialization. Values in the array element can be updated or modified but cannot be deleted....

Declaring and Initializing Arrays

The below-given surtaxes can be used to declare and initialize an array in Rust:...

Printing Elements of a Simple Array

To print all values in the array use the {:?} syntax of the println!() function. To compute the size of the array we can use the len() function....

Working with Arrays without Data Type

...

Array Default Values

...

Working with Loops on Array

The program below declares an array of 5 elements. Here we are not explicitly defining the data type during variable declaration. So, the array will be of type integer. To compute the size of the array we can use the len() function....

Using the iter() Function on Arrays

...

Concept of Mutable Array

Let us create an array and initialize all the values with the default value 0....

Passing Arrays as Parameters to Functions

...

Contact Us