我是 Golang 世界的新手。我试图理解自动引用的概念。
我对以下程序感到困惑?第一个和第二个有什么区别
- main 函数的第一行
age(20).print()
- 第二行和第三行
myAge := age(20)
myAge.print()
完整程序如下:
package main
import "fmt"
type age uint8
func (a *age) print() {
fmt.Println(a)
}
func main() {
age(20).print() // this line throws error
// however, the below line works properly
myAge := age(20)
myAge.print()
}
请帮助理解这两种方法之间的区别。我假设它们都是相同的。
最佳答案
这是编译器提供的便利。正如 calls 中提到的规范部分:
If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m()
这在 method Pointers vs Values 中有详细阐述。有效执行部分。
要确定什么是可寻址的,您可以引用Address operators规范部分。具体来说:
... 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.
回到你的例子,(a *age) print()
是 age
上的指针接收器。这意味着对 age
的完整调用变量是 &<expr>.print()
。这只能在 expr
时完成。是可寻址的。查看可寻址性要求:
-
myAge
是一个变量,它是可寻址的。 -
age(20)
是类型转换并且不可寻址。
忽略方法调用,您可以通过尝试以下操作轻松检查可寻址性:
_ = &age(20) // cannot take the address of age(20)
myAge := age(20)
_ = &myAge // works fine
关于pointers - Golang 自动引用,并不总是可以获得值的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62589461/