Arrays
This lesson introduces you to a compound data type, Arrays.
What Is an Array? #
An array is a homogenous sequence of elements. Being a compound type, it is used when the collection of values of the same type are to be stored in a single variable. In Rust, an array can only be of a fixed length. Like all other languages, each element in the array is assigned an index. By default, the first element is always at index 0.
Note: By default, arrays are immutable.
Define an Array #
To define an array in Rust, we have to define the type and size of the array.
To initialize an array, the array elements are enclosed in square brackets []
.
The following illustration explains the concept:
Press + to interact
#[allow(unused_variables, unused_mut)]fn main() {//define an array of size 4let arr:[i32;4] = [1, 2, 3, 4];// initialize an array of size 4 with 0let arr1 = [0 ; 4];}
- The array
arr
declaration on line 4 declares an array with elements