In this tutorial, we will learn how to pass structs to functions in Go by exploring two different methods: passing by value and passing by reference. These concepts are essential for controlling whether changes within a function affect the original data.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.
Defining the Structure
Begin by declaring the package and importing the required packages. Then, we define aCircle struct that contains four fields: x, y, radius, and area.
Passing Struct by Value
In the first method, we pass the struct by value. The functioncalcArea accepts a Circle instance as its parameter. Within the function, the area of the circle is computed using the radius field, but because the struct is passed by value, the changes remain local to the function and do not affect the original Circle instance.
Passing by value means that modifications made inside the function do not alter the original struct. This is useful when you want to ensure the integrity of the initial data.
calcArea.
Passing Struct by Reference
To modify the original struct within a function, pass the struct by reference using a pointer. In the modified version ofcalcArea, the function accepts a pointer to a Circle and directly updates the area field by dereferencing that pointer.
Passing by reference using pointers allows the function to alter the original data. This approach is ideal when you need to update the struct directly.
area field has been correctly updated:
Summary
In this guide, we examined two methods for passing structs to functions in Go:| Method | Description | Use Case |
|---|---|---|
| Pass by Value | The struct is copied, and modifications do not affect the original. | When you need to preserve the initial data integrity. |
| Pass by Reference | The function receives a pointer, allowing direct modifications to the original. | When updating the struct directly is required. |