Return pointer to local struct

后端 未结 2 579
深忆病人
深忆病人 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:28

    The Golang "Documentation states that it's perfectly legal to return a pointer to local variable." As I read here

    https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/EYUuead0LsY

    I looks like the compiler sees you return the address and just makes it on the heap for you. This is a common idiom in Go.

提交回复
热议问题