Structs are similar to tuples. They allow to hold related data together
Unlike a tuple each element in the Struct is assigned a name
Structs are comparable to the concept of dataclass
present in Python
To mutable even a single field in the struct, the entire struct has to become mutable
Values for fields in the struct can be provided in a order different from the definition order
When using a function to initialize a struct, if the names of the input parameters are the same as the the struct field names then the initialization shorthand
notation can be used
The fields of a struct can be initialized using the values of fields from another struct
Data Move
- When initializing structs using this method the Compound datatype values are moved to the newly created struct (Ownership - Rule 2)
- In the above example we would no longer be able to use the username field from user2
Struct fields can contain reference type data (Data that is borrowed from another variable) but this requires the use of lifetimes
Tuple Structs
Used to create a struct where the tuple needs to be assigned a name but assigning names to fields are too verbose for the scenario
Instead of field names the datatype of the fields are defined in the struct
Unit Structs
Defining and Instantiating Structs - The Rust Programming Language
Methods
Methods are functions that are defined within the context of the struct
The first parameter to a method is always self which points to the current instance
The methods that are tied to a struct need to be defined in a impl
(implementation) block
Multiple impl
blocks can also be created for an struct
Functions defined inside impl
block without a &self
reference are called associated functions
Associated functions are generally used to create constructors
Associated Functions are called using the ::
syntax with the struct name