Structures
On this page, we go over structures, and how they can be utilized.
What are structures?
In Radon, a structure is a user-defined data type that groups together different types of data (such as integers, and floats) into a single unit. This allows you to store and manipulate related data together, and also it allows you to create custom data types that better represent the problem you are trying to solve. A structure is defined using the "struct" keyword, followed by the structure name and a set of curly braces that enclose the members of the structure. There is only one member type that contributes to the overall unit of the structure. This type is called a field. Each field is a variable of a specific data type, and it has a name that can be used to access the field's value.
Structure Members
Structures, or structs as we will be calling them throughout the rest of this tutorial; contain members. Each member type has a special function that validates its existence.
Methods
Methods are blocks of code, that can be executed multiple times, by calling the method. A method can be either instance or static.
Method Declaration Syntax
Constructors
Constructors are special methods that are called when creating a new object, which we covered in the basics.
Constructor Declaration Syntax
Static Constructors
Static constructors, just like constructors, are special methods. However, static constructors are called when the runtime starts. Unlike constructors, static constructors cannot have parameters.
Static Constructor Declaration Syntax
Fields
Fields are the most important member type. They contribute to the overall span of the structure. Instance fields make up the entire memory span of the object.
Memory Layout
Structs are structured memory. They are a sequence of bytes that have meaning in the right context. But how exactly is memory laid out for structured?
Let's take for example a Color struct:
In this example, we've created a new Color object, that represents red. How would this look in memory? It would look like this: FFFF0000 That doesn't make a lot of sense though, so let's lay this out on a table:
A
FF
255
R
FF
255
G
00
0
B
00
0
With structures, the memory is laid out sequentially, meaning in the order of the field's declaration. Since we have four fields of type byte
. The size of the object will be 4 bytes.
Memory Span
The memory span of an object refers to the amount of memory that is allocated to that object during its lifetime. This includes both the memory required to store the object's data and any additional memory required for the object's metadata. When an object is created, memory is allocated for it on the heap (for dynamic allocation) or the stack (for static allocation). The amount of memory allocated for the object is determined by the size of the object's data, which is specific to the object's type. When an object is no longer in use, its memory is freed by the Garbage Collector.
Last updated