Sobes.tech
Senior

Where is memory allocated for a slice — on the stack or on the heap?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains a pointer to an array, a length, and a capacity. The slice itself (the structure with these three fields) is usually allocated on the stack, while the data it points to (the array) is allocated on the heap.

That is:

  • The slice header (pointer, length, capacity) is on the stack.
  • The slice elements are on the heap (if the array is large or dynamic).

This allows efficient handling of dynamic arrays without copying data when passing a slice by value.

Where is memory allocated for a slice — on the stack… - sobes.tech