Are local variables in go language on the heap or the stack?

Before discussing, let's look at the following code:

copy code

1 type treeNode struct {
 2     value int
 3     left, right *treeNode
 4 }
 5
 6 func createNode(value int) *treeNode {
 7     return &treeNode{value:value}
 8 }
 9
10 func main() {
11     root := createNode(10)
12     fmt.Println(root)
13 }

copy code

The above code createNode function returns the address of a local variable to the root in the main function, but fmt.Println normally prints out the contents of the newly created node. If this is written in C++, it is a very typical mistake: return the address of a local variable, the content of which will be automatically freed after the function exits, because it is on the stack.

So are the local variables of the go language on the stack or the heap? The go language compiler will do escape analysis to analyze whether the scope of the local variable escapes the scope of the function. If not, it will be placed on the stack; if the scope of the variable exceeds the scope of the function, then automatically on the stack. So don't worry about memory leaks, because the go language has a powerful garbage collection mechanism. This frees the programmer's memory usage constraints, allowing the programmer to focus on the program logic itself.

 

For the local variable from new, it is not necessarily placed on the heap, but whether it is placed on the heap or the stack is judged according to whether it exceeds the function scope. This is very different from the C language.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324144283&siteId=291194637
Recommended