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.
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:
Pointers in Go.
— Robin Moffatt š»šš„ (@rmoff) June 24, 2020
I grok *what* they are and *how* to use them (https://t.co/0nMV16r0Wz 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?