Basic Syntax
To access a field within a struct, use the following syntax:Example: Defining a Struct
Below is an example of a simple struct named Circle that has three fields: x, y, and radius. In the main function, we declare a variablec of type Circle.
Modifying Struct Fields
To modify the fields of theCircle struct, you simply access each field using the dot operator and assign a new value. In the example below, the values of x, y, and radius are all set to 5.
Remember that Go structs cannot be partially assigned. Each field must be explicitly set or initialized.
Handling Undefined Fields
Attempting to access a field that is not defined in the struct will result in a compilation error. For example, trying to accessc.area when area is not a field in the Circle struct will cause an error. The code snippet below demonstrates this issue:
Always ensure that you only access fields that are defined in your struct. Attempting to work with undefined fields will lead to compile-time errors.