The Rust Programming Language
The Rust Programming Language

The Rust Programming Language — Collections — Arrays

Ankit Tanna
3 min readOct 12, 2023

--

Just like Tuples and Structs, Array is another way you can store collection of values in a sequence. The only difference between Tuples/Structs and an Array in Rust is that Arrays are iterable where as Tuples and Structs are not iterable. Another significant difference is that Tuples and Structs can be a collection of different kinds of values where as an Array has to be a collection of same type of value.

let x: (i32, i32, bool) = (2001, 2023, false);

Arrays in Rust are quite different than any other languages that you have used. Refer below snippet to understand how you can define Arrays:

fn main() {
let mut years: [i32; 3] = [2021, 2022, 2023];
}

Observations:

  1. You need to declare the type and length of the array using [i32; 3].
  2. You can have a mutable or a non-mutable array.

The above array says that all of the elements have the type of i32. Another difference as compared to other languages is that Arrays in Rust have a hardcoded length at compile time.

Array has very similar features to what we did with Tuples and Struct. It can access value using index. It can be de-structured. Refer below code snippet:

fn main() {
let mut years…

--

--