Go 中的变量是否都分配在堆上?

Are all the variables in Go allocated on heap?

我是 Go 的新手,发现 return 函数中定义的局部变量的地址是可以的。这在 C 中显然是不可能的,因为局部变量在堆栈中。

所以我只是想知道为什么在 Go 中可以这样做?在 Go 中,局部变量在堆中?由于分配堆内存比堆栈昂贵得多,它会影响性能吗?是否可以在 Go 中的堆栈中分配局部变量?或者实际上 Go 中有堆栈内存?

There's a very clear answer to that question in the FAQ:

How do I know whether a variable is allocated on the heap or the stack?

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.

The storage location does have an effect on writing efficient programs. When possible, the Go compilers will allocate variables that are local to a function in that function'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.

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.

TLDR:你不应该在意。 Go 会为您处理分配。