Return pointer to local struct

Go

Go Problem Overview


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?

Go Solutions


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

Solution 2 - Go

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondemiView Question on Stackoverflow
Solution 1 - GoLily BallardView Answer on Stackoverflow
Solution 2 - GomasebaseView Answer on Stackoverflow