In this article, we’ll explore how to access and modify the fields of a struct in Go using the dot operator. The dot operator allows you to reference a specific field of a struct variable by following the variable name with a dot and then the field name.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
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.