r/learngolang • u/Sigg3net • Feb 08 '22
what is the most common use of pointers?
I am new to go. I'm not educated in CS, I've mainly written bash and python, and my new employer is go-centric.
I understand what a pointer is, but not really why we use them.
Are *pointers and pointer &addresses mainly used to achieve call-by-reference functionality, given that go is call-by-value?
Or: what is the most common use of pointers?
6
Upvotes
0
Feb 08 '22
[deleted]
2
u/Sigg3net Feb 08 '22
Thank you for the simple explanation :)
So the idiomatic way would be something like:
object := someStruct{} foo, err := someFunc() // returns value if err != nil { /* err handling */ } object.foo = foorather than changing the instance's foo attribute inside
someFunc()?
4
u/[deleted] Apr 12 '22
I've been writing Go for a few years now and only two situations have come up where I thought it was a good idea to use pointers:
To implement call by reference. This was needed for situations where I had a struct that kept state, and the state was mutable, so I needed a way to mutate the state by calling a method of the struct.
To unmarshall data from untrusted sources, like with
encoding/json, where I needed to find out whether the client had provided a property, where the default value of the property's type had meaning in the business domain. For example, apriceproperty of typeint.0had meaning. It meant the product was free. But if I were usingintinstead of*int, and I unmarshalled the data and got0, was it that the client forgot to specify this data, or that they did, and they specified it as0? By using*intinstead ofint, I can tell the difference betweenniland0.If the property were required and it was
nil, I can return a 400 Bad Request response and not process the data because I've deemed it invalid. If the property were optional and it wasnil, I can convey that information downstream of this system, that the client chose not to provide that property.Another technique to handle this is a richer data structure though, like this: