Rust Arrays

In Rust, an array is a special type of variable that contains multiple values of the same type. The following integer variable, ‘age’, has been defined and initialised with the value 30.

let age = 30;

If multiple ages need to be stored, instead of having a different variable for each, an array could be used. Arrays can be created in three different ways in Rust, with a data type, without a data type, or with default values.

Below is an example of an array with a data type of 'i8', that can hold four values, and is initialised with the values 30, 24, 53, and 19. To display an array in its raw form, ':?' must be placed within the curly brackets.

// Array with data type and size specified.
let ages:[i8; 4] = [30, 24, 53, 19];

// Display the array.
println!("Array of ages: {:?}", ages);

This produces the following output.

Array of ages: [30, 24, 53, 19]

The same array can be declared and initialised without specifying the data type or size. Both are implied by the type and number of values assigned to it.

// Array without data type and size specified.
let ages = [30, 24, 53, 19];

Finally, an array can be declared, with a data type and size specified, along with the same default value in each position in the array.

// Array with data type, size and default values specified.
let ages:[i8; 4] = [30; 4];

// Display the array.
println!("Array of ages: {:?}", ages);

Here, an array is declared with a size of four and type of 'i8'. Each value is also defaulted to 30.

Array of ages: [30, 30, 30, 30]

Each position in an array can be referred to by its index value, which starts at zero for the first value. This index can be used to both update and display the value contained within. Note that if an array is to be updated, then the 'mut' reserved word must be used, as with other variables.

// Array with data type, size and default values specified.
let mut ages:[i8; 4] = [30; 4];

// Display the array.
println!("Array of ages: {:?}", ages);

// Update the second value in the array.
ages[1] = 40;

// Display the updated array.
println!("Updated Array of ages: {:?}", ages);

The following is displayed.

Array of ages: [30, 30, 30, 30]
Updated Array of ages: [30, 40, 30, 30]

The index value can be used in a similar way to display a particular value.

println!("Second value in array: {}", ages[1]);

All the values in an array can also be processed one at a time using a 'for' loop.

for age in ages
{
    println!("{}", age);
}

Here, each age in the array is displayed on a separate line.

30
40
30
30