The Rust Programming Language — Collections — Arrays
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:
- You need to declare the type and length of the array using
[i32; 3]. - 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: [i32; 3] = [2021, 2022, 2023];
let first_year = years[0];
let [_, second_year, third_year] = years;
let x = 1;
let year_by_index = years[x];
// years[3] <-- compile time panic
// years[x] <-- run time panic if x > 2
years[2] = 2024;
}Observations:
- Arrays are fixed length at compile time
- If you try to access beyond the indexes available it will throw a compile time error.
- If you pass
xtoyearsit will not throw a compile time error because Rust does not know whatxis. Hence it throws a run time error when x exceeds 2.
You can also iterate over years. An array provides an iterable function called iter() which can be used to iterate over the array.
fn main() {
let mut years: [i32; 3] = [2021, 2022, 2023];
for year in years.iter() {
println!("Year: {}", year);
}
}Observations:
- You don’t need unwanted
()around the for loop like other languages - You need to access the iterable object of an array using
.iter()method.
Why is Array iterable and not Tuple or Structs? Well, going back to the top where we see that Array has same type of elements, Rust can be confident about the operations that can happen for each iteration (say adding 1 to each number in an array). Hence, Arrays are iterable where as Tuples and Booleans are not.
That’s it for Arrays in The Rust Programming Language. Please share your feedback in the comments section.
You can subscribe to my newsletter about The Rust Programming Language here. You can read about all the articles in this series here.






