Memory in Go is managed by a runtime ( goruntime ). This frees the developer from having to deal with device memory directly and transfers allocation and freeing (garbage collection and returning memory to the OS (scavenger)) responsibilities to runtime. There are two places in memory that Go works with - the heap and the stack. The garbage collector works only on the memory allocated in the heap, due to the “features” of the organization of memory on the stack.
Go runtime prefers to allocate memory on the stack, so most of the allocated memory will be there. Each goroutine has its own stack and, if possible, the runtime will allocate space in it. As an optimization, the compiler tries to carry out the so-called escape analysis, that is, to check that the function variable is not mentioned outside its scope. If the compiler manages to find out the lifetime of a variable, it will be placed on the stack, otherwise it will be placed on the heap. Usually, if a program has a pointer to an object, that object is stored on the heap. Unlike the stack, memory on the heap must be manually freed. In the case of Go, this is the responsibility of the garbage collector.
Go runtime uses three “tools” to work with memory:
They abstract memory handling, but are still not without flaws.
src/runtime/mgc.go)src/runtime/mgcmark.go)src/runtime/mgcsweep.go)
src/runtime/malloc.go)