The struct
keyword represents composite data types in C, C++, and Rust. A struct
is like a class only with attributes and no methods. We can use them to implement data structures in our programs.
Members of a struct
can be accessed via two methods:
- The dot operator is used when we don’t need to dereference (like when a structure hasn’t been dynamically allocated).
- The arrow operator is used when dereferencing, i.e., the
struct
is a pointer.
Note that we can only compare struct
field-by-field. Note that the equality operator in both languages produces a shallow copy.
Definition and initialisation
The struct
definition does not involve the allocation of memory. Memory is only allocated when struct
is instantiated through variable declaration or dynamic allocation.
We can also define an alias for a data structure so we can assign a name for an existing data type, either in the same statement or in a statement after the structure type is defined.
We can initialise a struct
in a single statement:
In Rust
Note that to modify the struct’s values, the entire instance must be mutable, i.e., specific fields cannot be mutable and others immutable.
In assembly
The space requirements of struct
tells the compiler how much memory to map out for each instance.