Golang in sixty seconds — Pointers

Two stormtroopers pointing to the distance
Photo by Saksham Gangwar on Unsplash

A pointer is the location in memory where a value lives. It's very important in Go to understand pointers as most parameters given to functions will be passed by value, not reference. This means that the following code may not do what you expect it to:

func add1(num int) {
  num = num+1
}
myNum := 1
add1(myNum)
fmt.Println(myNum)

This will print “1” to the console (you can try it here). A copy of myNum is made when it is passed to the function add1. So now there are two memory locations with a value of 1. The one used in the function will be updated to 2, but the original myNum stays the same. If we want the function to mutate myNum we must use pointers like so:

func add1(num *int) {
  *num = *num+1
}
myNum := 1
add1(&myNum)
fmt.Println(myNum)

All those asterisk's and ampersands are confusing, right? You can try ithere

Here's the cheat sheet I use to help me on a daily basis:

Richard Bell

Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.