Tutorial: Go (Golang) Pointers in 5 Minutes

In my previous Go articles I showed you how to setup Go on Ubuntu as well as how to create a couple different REST projects (here and here). Today, I’m going to go over how to use pointers and references in Go.

I’m assuming you already have Go up and running, if not make sure to do that first.

Let’s start with a very simple application that simply takes a value and runs a calculation on it.

You might have expected the output to have been 1100 however you need to keep in mind that by default when you pass an argument to a function in Go it will be copied by value. This simply means a “copy” of the val variable is used by the updateValue function.

Let’s fix this so that updateValue will change the val value. In order to do this we need to pass the val variable by reference. That is, we will pass in the address of the val variable and then updateValue can change that value.

You can see here I’ve used an asterix (Pointer) * and an ampersand (Reference) &. The updateValue function has been updated to accept an integer (someVal) that is a pointer. A pointer points to a memory address location and allows us to change the value. When we call the updateValue function now we need to send the reference (address) of the val variable. You can see in the updateValue function I don’t even need to name the variable val, I can call it whatever I want because its just a pointer.

Go also has a nifty function called new. When using the new function you pass in the type, like int, float32, etc. What new will return back to you is a pointer to a location in memory set aside that can hold the type you specified. A benefit of using new is you can simply pass the variable (pointer) without having to use the & operator.