First time posting here, but I wanted to get some feedback/corrections on a small blog post I made to help clear up my own confusions with the topic. I researched a lot for it, but I'm concerned I might be missing something in my fundamental understanding of the topic.
Here is a link to it, any feedback is appreciated: http://www.phizzle.space/golang/2017/01/27/go-pointer-receivers-vs-value-receivers.html
评论:
joncalhoun:
joncalhoun:First piece of feedback - variables in go are camel case or Pascal case, not snake case. Update
status_code
in your example to bestatusCode
phizzle5:Remaining feedback:
Read this: https://golang.org/doc/faq#methods_on_values_or_pointers - it covers the topic pretty well.
Mentioned in the previous link, but it might be worth noting that if you need a pointer receiver for a single method of your type, you should just use pointer receivers for all of the methods for consistency.
Technically there is a difference between a pointer receiver and a value receiver for slices. The former can adjust the length of the slice, whereas the latter cannot. Both can affect values of the array backing the slice, which is why your example works, but both cannot append a new item to the slice.
All in all the article reads well and does a pretty good job of introducing the differences between pointer and value receivers, but I definitely think the second point is worth stressing so that people know to keep their receivers consistent.
heraclmene:thanks for the detailed feedback! I did not know all that special info about slices.
phizzle5:When a method is a value receiver, it means that you cannot modify the struct fields because the struct is being passed by value.
You can, it will only modify that method's struct fields. It is also best practice not to mix pointer receivers and value receivers; use one or the other depending on your use case (as mentioned by /u/jancalhoun).
hobbified:Thank you!
phizzle5:I would say that a method has a pointer or value receiver, not that it is one. The "receiver" is the parameter that gets the object the method was called on.
Also, here's something I wrote a while back on the question of when you're able to call each type of method, and how they go towards satisfying interfaces.
alasijia:thanks for the share, will check it out.
hobbified:pointers are also values, so the terminology of value receiver is not good. A better alternative is "non-pointer receiver".
Receivers are just special parameters, which means they are also passed by value.
alasijia:It's used by the language spec, and everyone knows what it means.
indeed.
But there is not a definition for "value receiver" in spec.
