Heap and stack
The heap is the place where programming languages store global variables—the heap is where garbage collection takes place. The stack is the place where programming languages store temporary variables used by functions—each function has its own stack. As goroutines are located in user space, the Go runtime is responsible for the rules that govern their operation. Additionally, each goroutine has its own stack, whereas the heap is "shared" among goroutines.
In C++, when you create new variables using the new
operator, you know that these variables are going to the heap. This is not the case with Go and the use of the new()
and make()
functions. In Go, the compiler decides where a new variable is going to be placed based on its size and the result of escape analysis. This is the reason that you can return pointers to local variables from Go functions.
As we have not seen new()
in this book many times, have in mind that new()
returns...