Junior — Middle
Kes otsustab, kas lubatud paigutada teatud objekti mällu?
sobes.tech AI
Vastus AI-lt
Memory allocation of objects in Go (Golang) is determined by the compiler and runtime.
- The compiler decides where to place the variable: on the stack or on the heap, based on its scope and lifetime analysis (escape analysis).
- If the variable «escapes» from the function (for example, is returned or used after the function exits), it is placed on the heap.
- Otherwise, it is placed on the stack, which is faster.
Thus, the decision to place an object in memory is made by the compiler at compile time, and the runtime manages allocation and garbage collection for objects on the heap.