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
).
这是为什么?为什么接收T
的方法属于为*T
设置的方法,反之则不然?
最佳答案
来自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.
顺便说一下,一个带有指针接收者的方法可以改变它的接收者,就像它可以改变一个指针参数一样。将非指针接收器作为指针接收器传递(假设这是可能的),允许方法更改它,这不应该。
建议对一种类型的所有方法使用一种一致的接收器类型,并避免混合使用指针和直接接收器。还建议对大型类型使用指针接收器。
关于methods - T 和 *T 的方法集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10672729/