我正在阅读《The Go Programming Language》这本书。这对我们(相当)有经验的程序员来说非常好,并解释了其他语言的交集之间的差异——但我发现了一个我不完全理解的案例。
我对 C++ 非常了解,而且我知道 Go 调用(在 C++ 中会被称为)右值/x 值是“不可寻址的”。只有“变量” [GOPL 的话] 是可寻址的。
好吧,很公平;这是有道理的。
因此,例如,这是非法的(根据第一次打印的第 159 页)
Point{1, 2}.ScaleBy(2) // compile error: can't take address of Point literal
因为 (*Point).ScaleBy
将 *Point
作为接收参数,而 Point
文字是不可寻址的。
(如果您还没有读过这本书,Point
是一个包含字段 X, Y float64
的结构。
但是,在第 162 页,我们有
type ColoredPoint struct {
*Point
Color color.RGBA
}
p := ColoredPoint(&Point{1, 1}, red)
// ...more code ...
这显然是有效的并且可以编译。
问题:
为什么第二种情况下的 Point
文字是可寻址的?
它是为了方便而特例,还是我遗漏了全局?
最佳答案
&T{}
表示法在第 103 页的第 4.4.1 节“结构文字”中进行了解释:
Because structs are so commonly dealt with through pointers, it’s possible to use this shorthand notation to create and initialize a struct variable and obtain its address:
pp := &Point{1, 2}
It is exactly equivalent to
pp := new(Point) *pp = Point{1, 2}
but
&Point{1, 2}
can be used directly within an expression, such as a function call.
很高兴您还喜欢这本书。
关于pointers - Go struct literals,为什么这个是可寻址的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793289/