Sobes.tech
Middle

Does an internal slice created inside a function when exceeding capacity get created on the stack or on the heap?

sobes.tech AI

Answer from AI

In Go, when an internal slice is created inside a function and exceeds its capacity, a new array with an increased size is allocated. This new array is allocated on the heap, and the slice points to this array.

The slice itself is a structure with three fields (pointer to the array, length, capacity), which is usually stored on the function's stack. However, the data it references (the new array) is placed on the heap to preserve it after the function exits and to enable dynamic resizing.