Rust – Concept of Structures
Structures are basically user-defined type mainly used for grouping different data types together. It overcomes the limitation of a traditional array that can only contain elements of the same data type. A structure can also contain a structure in itself. In Rust, structures are similar to tuples, but structure elements are easily accessible since they are named instead of indexed in the case of tuples.
In Rust, structures are of three types
- Typical C like structure
- Tuple struct: It is similar to a tuple, where the fields are un-named but with added functionalities.
- Unit struct: These are field-less structures i.e. do not contain data. It is useful in cases where we just want to implement the trait on some type but don’t have data.
How to define a structure?
A structure is defined by struct keyword followed by the key-pair elements.
Here we have defined a Student structure using the struct keyword and its elements -“name”, “roll” and “dept”, along with their expected data types. We have also defined the unit struct and the tuple struct. When we defined the structure, no memory is allocated to it. Only when we will initialize it then it will be allocated.
Now, we will initialize our Student structure. Structure elements are accessed using the “.” (dot) operator.
Updating values of a defined structure
Since we want to update the value of a structure so the variable by which we are initializing it i.e. student1 in the above case should be declared mut (a variable that can be updated), otherwise by default it is immutable (can’t be updated).
As earlier said, we can use a structure within another structure. Let us see.
Here we tried to add address structure into student structure. One thing to be noted is that the addr structure should be defined before the student structure and the same goes during initialization. Notice the method used to access the elements of a structure that is part of another structure. For this, we have used the dot operator twice as in student1.addr.pin.
Defining methods for a structure
The area of the triangle is = 7.5
We started an impl (implementation) block, within which we defined the method area for the triangle. We passed the address of the instance of the struct to the function and used self to refer to it.