Heap or stack?
According to the official FAQ [1],
From a correctness standpoint, you don't need to know. Each variable in Go exists as long as there are references to it. The storage location chosen by the implementation is irrelevant to the semantics of the language.
In the current compilers, if a variable has its address taken, that variable is a candidate for allocation on the heap. However, a basic escape analysis recognizes some cases when such variables will not live past the return from the function and can reside on the stack.
Yet if you are so determined to find out where actually Go allocates the variables, here is a quick trick that you can use, suggeseted here [2]
If you need to know where your variables are allocated pass the "
-m
" gc flag to "go build
" or "go run
" (e.g.,go run -gcflags -m app.go
).
Here is an example running memory analysis on the heap escape.
// go run heap-stack.go
package main
import "fmt"
type Foo struct{
x int
}
func main(){
var i = 0
var foo = Foo{i}
fmt.Println(foo.x) // use x so that Go won't complain
}
We will get this as following result
# command-line-arguments
./heap-stack.go:10: foo.x escapes to heap
./heap-stack.go:10: main ... argument does not escape
0
Since the struct foo is sent to a function, the Go complier put foo.x on the heap, thus escaping the stack scope.
[1] https://golang.org/doc/faq#stack_or_heap
[2] http://devs.cloudimmunity.com/gotchas-and-common-mistakes-in-go-golang/index.html#stack_heap_vars