Return pointer to local struct

后端 未结 2 573
深忆病人
深忆病人 2020-11-30 23:55

I see some code samples with constructs like this:

type point struct {
  x, y int
}

func newPoint() *point {
  return &point{10, 20}
}

2条回答
  •  [愿得一人]
    2020-12-01 00:17

    Go performs pointer escape analysis. If the pointer escapes the local stack, which it does in this case, the object is allocated on the heap. If it doesn't escape the local function, the compiler is free to allocate it on the stack (although it makes no guarantees; it depends on whether the pointer escape analysis can prove that the pointer stays local to this function).

提交回复
热议问题