patterngoCritical
Return pointer to local struct
Viewed 0 times
pointerlocalreturnstruct
Problem
I see some code samples with constructs like this:
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?
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?
Solution
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).
Context
Stack Overflow Q#13715237, score: 140
Revisions (0)
No revisions yet.