T和*T的方法集合

huangapple go评论85阅读模式
英文:

Method sets for T and *T

问题

Golang语言规范中指出:

> 任何其他类型T的方法集由所有接收器类型为T的方法组成。相应指针类型*T的方法集是所有接收器为*TT的方法的集合(也就是说,它还包含了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.

huangapple
  • 本文由 发表于 2012年5月20日 18:41:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/10672729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定