The Golang language specification states:
The method set of any other type T consists of all methods with receiver type
T
. The method set of the corresponding pointer type*T
is the set of all methods with receiver*T
orT
(that is, it also contains the method set ofT
).
Why is this? Why do the methods receiving T
belong to the method set for *T
but not vice versa?
From the FAQ:
If an interface value contains a pointer *T, a method call can obtain a value by dereferencing the pointer, but if an interface value contains a value T, there is no useful way for a method call to obtain a pointer.
By the way, a method with pointer receiver can change its receiver, just like it can change a pointer parameter. Passing a non-pointer receiver as a pointer one (assuming this is possible), allows the method to change it, which should not.
It is recommended to use one consistent receiver type for all methods of a type and avoid mixing pointer and direct receivers. It is also recommended to use pointer receiver for large types.