英文:
Method sets for T and *T
问题
Golang语言规范中指出:
> 任何其他类型T的方法集由所有接收器类型为T
的方法组成。相应指针类型*T
的方法集是所有接收器为*T
或T
的方法的集合(也就是说,它还包含了T
的方法集)。
为什么会这样呢?为什么接收器为T
的方法属于*T
的方法集,但反过来却不成立?
英文:
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
or T
(that is, it also contains the method set of T
).
Why is this? Why do the methods receiving T
belong to the method set for *T
but not vice versa?
答案1
得分: 6
从FAQ中:
> 如果一个接口值包含一个指针*T,方法调用可以通过解引用指针来获取值,但是如果一个接口值包含一个值T,方法调用无法以有用的方式获取指针。
顺便说一下,具有指针接收器的方法可以更改其接收器,就像它可以更改指针参数一样。将非指针接收器作为指针接收器传递(假设这是可能的),允许方法更改它,这是不应该的。
建议为类型的所有方法使用一致的接收器类型,并避免混合使用指针和直接接收器。对于大型类型,建议使用指针接收器。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论