DEV Community

Robin Moffatt
Robin Moffatt

Posted on • Originally published at on

Learning Golang (some rough notes) - S01E01 - Pointers

👉 A Tour of Go : Pointers

I’ve never used pointers before. Found plenty of good resources about what they are, e.g.

But why? It’s like explaining patiently to someone that 2+2 = 4, without really explaining why would we want to add two numbers together in the first place.

(side note: I bet a ton of devrel material could be made more accessible by addressing the huge number of assumptions that are made, explicit and implicit, in explanations given)

My colleague Ricardo Ferreira gave me this great explanation:

Pointers in Go has to do with three main things:

Garbage Collection

Go is a garbage collected language just like Java. However, it uses of some less sophisticated algorithms to reclaim memory space than Java that tries to figure out too much doing heap transverse and thus spending too much CPU on it. Go is meant to provide better performance and because of this it tries to share the responsibility with the developer about how to track references. And if a developer uses a pointer; it is the indication about which references need to be reclaimed given its scope. It uses something called reference counting to figure that out.

Encapsulation (Information Hiding)

Pointers are particularly good for structs, which represents complex data structures. By returning structs rather than the actual value developers can ensure that only the function that created the struct can act upon it.


You better than anyone will understand this. Structs represents records and therefore their occurance needs to be immutable. You can’t change what happened in the past and thus; you are not supposed to change structs — unless the function that created the struct provides a write operation. So in Go, we use the concept of interface methods that are nothing more than function pointers to a struct.

I also got some useful feedback from people on Twitter:

Pointers in Go.

I grok *what* they are and *how* to use them ( sorted me out there) - but can a kind soul point me to a good resource that explains *why* I would use them? Why don't I just pass variables around instead?

— Robin Moffatt 🍻🏃🥓 (@rmoff) June 24, 2020

Pointers are just indirection. For size, think of loading GB of data. Without indirection, you'd have to copy all of it every time. Pointer lets you say "here's where to find the data" rather than "here's a copy of the data".

— ewencp (@ewencp) June 24, 2020

The main reason is performance and memory management. Say you have a large complex object that you want to use as a parameter to a method. If you don't use a pointer then the entire object is copied and the copy is fed into the method. This means allocating and configuring a ...

— Ray Skywalker (@raysaltrelli) June 24, 2020

Top comments (1)

pg_77 profile image
Perry Grewal • Edited

I'm working on understanding this as well along with empty interfaces.