pointers - Go struct literals,为什么这个是可寻址的?

标签 pointers go struct language-lawyer composite-literals

我正在阅读《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/

相关文章:

C++ 和运算符优先级

c++ - 如何提取未命名结构的类型以在结构本身内创建新类型?

c - 我无法弄清楚我的指针错误

sql - 高效地将一对多多对多数据库映射到 Golang 中的结构

go - 使用 map , slice 或 channel 类型进行类型安全

global-variables - 程序必须访问包中的全局变量

c - 任何类型的一般排序,与结构作斗争

pointers - 在 Pascal 中使用 Dispose

c - 这里的负指针值是多少?

c - 从C中的函数获取返回值