&quot;When possible, the Go compilers will allocate variables that are local to a function in that function&#x27;s stack frame. However, if the compiler cannot prove that the variable is not referenced after the function returns, then the compiler must allocate the variable on the garbage-collected heap to avoid dangling pointer errors. Also, if a local variable is very large, it might make more sense to store it on the heap rather than the stack.<p>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.&quot;<p><a href="https:&#x2F;&#x2F;golang.org&#x2F;doc&#x2F;faq#stack_or_heap" rel="nofollow">https:&#x2F;&#x2F;golang.org&#x2F;doc&#x2F;faq#stack_or_heap</a>