Junior — Middle
Millised on mälutüübid ja kuidas nad omavahel suhtlevad?
sobes.tech AI
Vastus AI-lt
In Go (Golang), the main types of memory and their interaction are as follows:
-
Stack — stores local variables of functions. The stack is quickly allocated and freed during function calls and returns.
-
Heap — used for dynamic memory allocation, for example, for objects that live longer than the current function. Go has a garbage collector that manages heap cleanup.
-
Global/static memory — for global variables and constants.
Interaction:
- When a function is called, local variables are placed on the stack.
- If a variable needs to live longer, the compiler can "escape" it to the heap (escape analysis).
- The garbage collector automatically frees heap memory when objects become unreachable.
Example:
func foo() *int {
x := 10
return &x // x "escapes" to the heap because a pointer is returned
}
Here, the variable x will be placed on the heap so that the pointer remains valid after the function exits.