Learn about Arrays, one of Rust's compound data types.
Array is a Rust data type that is used to store multiple values of the same type.
Arrays are defined using square brackets, for example:
// An array of 3 booleans
let checks: [bool; 3] = [true, false, true];
Array is a Rust data type that is used to store multiple values of the same type.
Arrays are defined using square brackets, for example:
// An array of 3 booleans
let checks: [bool; 3] = [true, false, true];
Just like tuples, arrays have a fixed length. Their values must always contain the same number of elements as mentioned in the type signature:
let array_with_2_ints: [i32; 2] = [1, 2];
let array_with_3_ints: [i32; 3] = [1, 2, 3];
// This is invalid because the value has < 3 elements
// let array_with_3_ints: [i32; 3] = [1, 2];
// This is invalid too because the value has > 3 elements
// let array_with_3_ints: [i32; 3] = [1, 2, 3, 4];
Unlike tuples, elements in array need to be of the same type.
// Invalid because the second value isn't an integer
// let array_of_ints: [i32; 2] = [1, 'A']
// Valid because both values are integers
let array_of_ints: [i32, 2] = [1, 2]
In most cases, you don't need to annotate the type for an array. If a value is surrounded by square brackets and no type annotation is present, Rust infers the type based on the values used.
// Here the inferred type is [i32; 3]
let array_with_3_ints = [1, 2, 3];
Similar to tuples, the elements in an array can be accessed using two primary methods — indexing and destructuring.
let array_of_3_ints = [1, 2, 3];
// Indexation
array_of_3_ints.0 // => Returns 1
array_of_3_ints.1 // => Returns 2
array_of_3_ints.2 // => Returns 3
// Destructuring
let [a1, a2, a3] = array_of_3_ints; // Assigns a1 to 1, a2 to 3 and a3 to 3
In this concept we covered Arrays, a Rust data type that is used to group multiple values of the same type.
[int32; 4]
array_of_values.0
, array_of_values.1
let [a1, a2, a3] = array_of_values
You can read more about the array data type in the Data Types section of the Rust book.