methods - T 和 *T 的方法集

标签 methods interface go receiver

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).

这是为什么?为什么接收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/

相关文章:

go - 我无法将数据分配给 []map[string]interface{}

C# 参数化方法数组或参数化方法列表

javascript 检查对象是否实现了 HTMLAnchorElement 接口(interface)

Java - 调用从数组返回整数字符串的方法

android - 谷歌播放界面

c++ - 具有双向接口(interface)的基于 DLL 的应用程序框架 (Windows)

go - 在 Go 中按值传递还是按引用传递效率更高?

sockets - 静态html页面直接创建WebSocket连接golang服务器

java - 我应该始终在 Java 类中使用 getter/setter 方法,还是有时可以使用公共(public)属性?

java - 使用方法和多个类的一副纸牌