The Rust Programming Language — Collections — Summary
This article summaries all the concepts that we learnt under Collections, i.e. Tuples, Structs, Array and their representation in Memory.
In Rust, only Arrays can be iterated over as Rust has the confidence that all the elements inside of an array are of same type. Tuples and Structs cannot be iterated over as they can be composed of different types of data. Array gives you an iterable object using .iter() method which can be used to iterate over. The syntax of iteration is quite similar to other languages barring the fact that it does not have extra parenthesis around the looping expressions, for e.g. for year in years.iter().
There are 2 kinds of tuples. A tuple is usually a collection of 2 or more values. for example (i32, i32) for (10, 20) is a tuple. There is also a empty/blank tuple which usually refers to something similar like void in other programming languages.
Structs on the other hand are like a mixture of interface and a class from TypeScript. When declaring a struct in Rust you need to explicitly mention the name of the Struct before declaring the value. for e.g. Point {x: 1, y: 2, z: 3} is a struct of type Point.
Structs are label based, i.e. Point.x, Point.y, Point.z, where as Tuples and Arrays are index/position based Point.0, Point.1, Point.2.
All the Arrays, Structs and Tuples are fixed length at compiled time. Their structure cannot be altered. They are mutable though using mut keyword which allows you to update the value inside the Arrays, Structs and Tuples.
Finally, Arrays, Structs and Tuples are represented exactly the same way in the memory. So, if you had below declarations:
let myArray: [i32; 3] = [1, 2, 3];
let myStruct: Point = Point {x: 1, y: 2, z: 3};
let myTuple: (i32, i32, i32) = (1, 2, 3);All 3 of the variables would have the same memory in terms of sequence of bits.
That’s it for Collections 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.






