Skip to main content
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.

Defining the Structure

Begin by declaring the package and importing the required packages. Then, we define a Circle 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 function calcArea 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.
When you run this program, the struct’s values remain unchanged after calling 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 of calcArea, 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.
Upon execution, the output demonstrates that the area field has been correctly updated:

Summary

In this guide, we examined two methods for passing structs to functions in Go: Understanding the difference between these methods is crucial for managing data and memory efficiently in Go programming. That concludes our exploration of passing structs to functions in Go. In our next article, we will dive deeper into advanced topics related to struct operations and memory management in Go. For more detailed tutorials and Go programming tips, be sure to explore our Go Documentation.

Watch Video