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.
我的翻譯結(jié)果:
? ? ? ?我怎么知道一個(gè)變量是分配在堆上還是棧上?
? ? ? ?正確的觀點(diǎn)是,你不需要知道。go語言中的每一個(gè)變量,它的生命周期和引用它的周期一樣長。該語言的語義和實(shí)現(xiàn)時(shí)選擇的存儲(chǔ)位置,是沒有關(guān)系的。
? ? ? ?在編寫高效率的程序時(shí),存儲(chǔ)位置的確會(huì)有影響。如果可以,go語言編譯器將會(huì)分配函數(shù)的局部變量到函數(shù)的棧幀上。然而,如果編譯器不能證實(shí)局部變量在函數(shù)返回后,不會(huì)再被引用,編譯器將必須分配該變量到垃圾回收堆上,以避免出現(xiàn)懸掛指針錯(cuò)誤。如果一個(gè)局部變量非常大,那么存儲(chǔ)在堆上比存儲(chǔ)在棧上也更加合理。
? ? ? ?在當(dāng)前的編譯器里,如果一個(gè)變量的地址被調(diào)用了,這個(gè)變量將會(huì)候選分配在堆上。然而,一個(gè)基本轉(zhuǎn)義分析會(huì)識(shí)別一些情況。在這些情況里,變量不會(huì)存活到函數(shù)返回,這些變量將分配到棧上。