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条)

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误