Learning Golang (some rough notes) - S01E01 - Pointers

Published by in Go, Golang, Pointers at https://rmoff.net/2020/06/25/learning-golang-some-rough-notes-s01e01-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:

  1. 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.

  2. 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.

  3. Immutability

    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:


TABLE OF CONTENTS