109

I see some code samples with constructs like this:

type point struct {
  x, y int
}

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

I have C++ background and it seems like error for me. What are the semantic of such construct? Is new point allocated on the stack or heap?

phuclv
  • 37,963
  • 15
  • 156
  • 475
demi
  • 5,384
  • 6
  • 37
  • 57

2 Answers2

132

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

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
  • 16
    Here's a blogpost (disclaimer: which I wrote) that looks into Go's escape analysis a bit more closely: http://www.scvalex.net/posts/29/ – scvalex May 03 '13 at 12:07
  • 1
    @LilyBallard didn't fully get your answer. You mean that proving the fact of escaping pointer is always possible, while proving the fact of NOT escaping is not? – mangusta Sep 11 '20 at 10:31
  • 3
    working link to scvalex post in 2022: https://web.archive.org/web/20160923043317/https://www.scvalex.net/posts/29/ – Max Apr 27 '22 at 04:30
21

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.

Alex Bitek
  • 6,529
  • 5
  • 47
  • 77
masebase
  • 4,915
  • 3
  • 24
  • 20