In go one can define a method for a pointer receiver, as well. And Go can interpret the code syntax as follows:
In definition of the method, only writing the pointer type for the receiver is enough, inside the function definition you need not to dereference the pointer to access the very object in memory you want to access.
In function call, you do not need to call the function on a pointer type, on a reference I mean. Go can understand that you mean it.
type Box struct {
color string
}
var b Box
Based on that what is the reason for the golang code snippets are equivalent below? Are there a different reason other than convenience or code shorthand?
Go way, but the classical C way works, as well:
func (b *Box) setColor(c string) {
b.color = c
}
b.setColor("blue")
Classical C way:
func (b *Box) setColor(c string) {
(*b).color = c
}
(&b).setColor("blue")
It is as you say simply shorthand:
From the spec
As with method calls, a reference to a non-interface method with a pointer receiver using an addressable value will automatically take the address of that value: t.Mp is equivalent to (&t).Mp.
And method calls:
A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()