When and Where to Use Pointers in Go

submited by
Style Pass
2024-10-21 01:00:07

When declaring variables in Go, we usually have two syntax options: In some scenarios, pointers; in others, reference; sometimes, either. It’s great to have choices, but it is also confusing sometimes as to which one in which scenario.

To be more reasonable in choice-making, I started from pointers, walked through their natures, and summarized some rules in using them in Go.

The data is stored in the memory when the program runs and each has a number- the memory address, which can be assigned to a pointer, and through which we can find the data stored in memory.

A pointer variable, a variable that stores a pointer, can be converted with the real data in the memory address through the two operators of & and *.

In modifying the input parameters, reference type variables can no longer work, and you must use pointers, such as the common swap method in algorithm testing.

In this example, the field a of struct A cannot be modified by the method if it is not directly accessed viaa1.a, but can be done in subsequent methods(B.b) with pointers. Try it!

Leave a Comment