Pointer to a struct in GoLang

Pointers are a useful entity that stores a memory address in it. Structs are the building blocks of data structures in Go. In this post, we are going to explore pointers to a struct in GoLang.

Pointer to a Struct Syntax

The syntax of a pointer to a struct is just like any other pointer. It is of the same form as others. Here is the syntax in use.

// declare the struct
type Book struct{
        Name string
        Author string
}

// declare the pointer
var pB *Book
alice := Book{"Alice in Wonderland", "Lewis Carroll"}

// assign the pointer
pB = &alice

Accessing fields of the Struct using the Pointer Variable

Accessing the fields through the pointers is really easy and very straightforward. It is the same as if we are accessing via the struct itself.

import (
	"fmt"
)

type Bird struct{
	Species string
}

func main() {
	crow := Bird{"Crow"}
	var pBird *Bird
	pBird = &crow
	
	// access the data using dot identifier
	fmt.Println(pBird.Species)      // Crow
}

Passing as Arguments and Data Mutability

When the size of data we are going to manipulate is significantly larger then we use pointers in the function parameters. It is a common practice in many different programming languages. In Go, we can do the same.

We can simply pass a pointer to a struct in the function and then manipulate the struct using the function via the pointer. Let’s see how one would do that.

import (
	"fmt"
)

type A struct{
	B string
}

func change(a *A){
	a.B = "B"
}

func main() {
	a := A{"A"}
	fmt.Println(a)   // {A}
	change(&a)
	fmt.Println(a)   // {B}
}

As can be seen, the function mutates the original value in the struct as well. This is a very important property of using pointers as arguments. What happens is that, instead of changing it locally, the pointer changes it at the original value. This is extremely useful since we want to change the original rather than a copy of it.

Benefits of using a Pointer to a Struct

A pointer is a data type that stores a memory address. When we want to manipulate something via its address, we are doing it in the most efficient way. Instead of taking a copy of it, we are changing the original value itself. So, we must be cautious as well. Even though it is a more efficient way it does come with a cost.

The struct is a way to store structured data and manipulate it. When we want to manipulate structs directly we should try using their pointers instead.