- Structs consist of related items that potentially have different data types.
- Structs are similar to tuples in this regard. However, unlike tuples, you must define the data type of the item within the struct
- Structs help to create custom data types.
- Let’s consider a real life example. You know that a rectangle has two measurements, width and height. Suppose you have several rectangles which you can name. Once you have declared a rectangle items within the struct, you can initialize the values according to the type of rectangle. Suppose the dimensions of a rectangle may vary according to the color of the rectangle.
Structs are declared using a struct keyword followed by the name of the struct and then the body of the struct enclosed within curly braces. Within the body, the items of the struct aredefined as a key: value pair where keys are the items of the struct and value is the data type of each item.
Note: The struct construct can be declared anywhere, above or below the function that initializes it.
- The name of the struct should be in PascalCase, meaning, the first letter of each word in a compound word is capitalized.
- If this case is not followed, a warning, ⚠️, is generated by the compiler.
Note: The order in which you assign values to items does not matter.
To access any value from the struct write the struct name followed by the . operator and then the name of the item to be accessed.
Note: A struct instance is immutable by default. Therefore it cannot be updated unless made mutable. However, the values can be accessed.
A struct instance can be made mutable by adding a mut keyword after the let followed by the instantiation of the struct. Now that the struct instance is mutable, any item can be accessed using the dot operator and the value of the item can be updated.
The following example creates a struct named Course and defines three items of it: course name, course level, and course code.
Test your understanding of the basics of structs
- The values of struct can be accessed through a:
. dot operator
 subscript notation
- the name of the struct should be in which case to avoid compiler warning?