Let’s get an overview of the Go garbage collector and learn about heaps and stacks.

Installing Go

If we are going to install Go for the first time, we can start by going here. However, there is a big chance that our UNIX variant has a ready-to-install package for the Go programming language, so we might want to get Go by using our favourite package manager.

This appendix is all about the Go Garbage Collector (GC). This crucial part of Go can affect the performance of our code more than any other Go component. We will begin by talking about the heap and the stack.

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. Because 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 we create new variables using the new operator, we 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 we can return pointers to local variables from Go functions.

Note: As we have not seen new() in this course many times, keep in mind that new() returns pointers to initialized memory.

Coding example

If we want to know where the variables of a program are allocated by Go, we can use the -m GC flag. This is illustrated in allocate.go—this is a regular program that needs no modifications in order to display the extra output because all details are handled by Go.

Get hands-on with 1200+ tech skills courses.