A hands-on look at how pointers work in Go, when to use them, and how they behave with arrays.
Introduction
Pointers have a reputation for being tricky, mostly thanks to languages where they come with pointer arithmetic, manual memory management, and a long list of ways to crash your program. Go takes a much calmer approach. Pointers in Go are simple, safe, and explicit, and once you understand them you will write faster, more predictable code.
In this post we will cover:
What a pointer is and how to use & and *
Pass-by-value vs. pass-by-pointer
Pointers with structs
Pointers with arrays (with full examples)
Common pitfalls and when to use pointers
What Is a Pointer?
A variable stores a value. A pointer stores the memory address of a value.
Think of a house. The house itself is the value. The street address written on a piece of paper is the pointer. If you hand someone a photocopy of the house (a copy of the value), they can repaint their copy all day and your house stays the same.…