In many languages, local variables are located in call stack
In JavaScript/Python, only closure variables are located in heap, because they must live beyond the function calls, they are created.
In GO, some GO types(like slice type []int
) do reference other parts of memory, like JavaScript/Python.
In GO, not all types of variables hold references, like Javascript/Python.
For example,
1) [3]int
type variable b
directly stores an array of int
's, like C, except that C allows to get access of each array element location using C syntax &b[index]
, for more control
2) int
type variable c
directly stores an int
value, like C, except that, C gives more control by providing syntax(&c
) to get location access.
In GO, my understanding is, for local variables to be on heap/stack depends on applying compiler's escape analysis in example code(below),
func foo() []int {
// the array lives beyond the call to foo in which it is created
var a [5]int
return a[:] // range operator
}
that tells the compiler that variable a
lives beyond its scope, so allocate in heap, but not stack.
Question:
Does the variable a
get allocated in heap?
In Go, you are supposed to trust the compiler to make the best decision. It will allocate memory on the stack if possible. See also the FAQ:
Without optimization (inlining), yes
a
will be allocated in the heap. We can check the escape analysis by passing-gcflags='-m'
(https://play.golang.org/p/l3cZFK5QHO):We see that the compiler decided to allocate
inlined.a
on line 5 andno_inline.b
on line 10 on the heap, because they both escape their scope.However, after inlining, the compiler noticed that the
a
does not escape any more, so it determines the variable can be allocated on the stack again (line 18).The result is that the variable
a
is allocated on themain
goroutine's stack, while the variableb
is allocated on the heap. As we can see from the output, the address ofb
is on 0x1043xxxx while all other are on 0x1042xxxx.