返回指向本地结构的指针

我看到一些具有如下结构的代码示例:

type point struct {
x, y int
}


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

我有 C + + 的背景,这对我来说似乎是个错误。这种结构的语义是什么?在堆栈或堆上是否分配了新点?

31204 次浏览

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.

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