doujie7497 2016-11-24 19:17
浏览 67
已采纳

转到struct字面量,为什么这个地址可寻址?

I am reading the book "The Go Programming Language". It is very good for us (rather) experienced programmers and explains the differences between the intersection of other languages -- but I've found a case which I do not understand fully.

I know C++ sufficiently good, and I understand that Go calls (what in C++ would be called) rvalues/xvalues "non-addressable". Only "variables" [GOPL's words] are addressable.

OK, fair enough; it makes sense.

And therefore, for instance, this is illegal (according to page 159 in the first printing)

Point{1, 2}.ScaleBy(2) // compile error: can't take address of Point literal

because (*Point).ScaleBy takes a *Point as a receiver argument, and a Point literal is non-addressable.

(If you haven't read the book, Point is a struct with the fields X, Y float64.

However, on page 162, we have

type ColoredPoint struct {
    *Point
    Color color.RGBA
}

p := ColoredPoint(&Point{1, 1}, red)
// ...more code ...

which apparently is valid and will compile.

Question:

Why is the Point literal in the second case addressable?

Is it a special case for convenience, or am I missing something in the big picture?

  • 写回答

3条回答 默认 最新

  • dora12345678 2016-11-28 01:52
    关注

    The &T{} notation is explained in Section 4.4.1, Struct Literals, on page 103:

    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.

    Glad you're otherwise enjoying the book.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于#深度学习#的问题:2708)输出:邻接矩阵A 或者 节点索引方式:通过随机游走或者其他方式,保持节点连接类似下图(语言-python)
  • ¥15 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥15 用js遍历数据并对非空元素添加css样式