go - 当接收者方法 T 不能接受 *T 时?

标签 go

Go 官方网站 writes as follows :

As the Go specification says, the method set of a type T consists of all methods with receiver type T, while that of the corresponding pointer type *T consists of all methods with receiver *T or T. That means the method set of *T includes that of T, but not the reverse.

This distinction arises because 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 safe way for a method call to obtain a pointer. (Doing so would allow a method to modify the contents of the value inside the interface, which is not permitted by the language specification.)

Even in cases where the compiler could take the address of a value to pass to the method, if the method modifies the value the changes will be lost in the caller.

我的问题是,编译器何时不能将值传递给指针接收器值?

最佳答案

Addressable 定义于 https://golang.org/ref/spec#Address_operators :

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

计数器示例包括映射值和函数:

func f() {}

func main() {
    var m map[string]string
    p1 := &m["foo"] // cannot take the address of m["foo"]
    p2 := &f        // cannot take the address of f
}

关于go - 当接收者方法 T 不能接受 *T 时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58688655/

相关文章:

go - Sonarqube 是否支持 GO lang,如果不支持,那么该功能何时到位

go - 如何使用具有两个不同名称(短名称和长名称)的标志

go - 如何从一个字节中解压缩 2、2 和 3 位

ssl - 如何显示网站证书的公钥

json - 使用 golang 将 xml 转换为 swagger 2.0 规范

json - 如何在 Golang 中获取 JSON 唯一字段的名称和深度嵌套的子字段的值?

go - 如何从另一个函数返回函数?

go - 无法在 mac os X 上为 golang 运行 zmq,未知问题

go - 返回字符串作为模板

regex - Go - 正则表达式操作