Sobes.tech
Senior

When a slice is re-declared inside a function beyond its capacity — is it allocated on the heap or on the stack?

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. When you add elements and exceed the current capacity of the slice, a new array with increased capacity is allocated.

This new array is allocated on the heap, not on the stack, because its size and lifetime cannot be determined at compile time. After that, the slice inside the function points to this new array on the heap.

Example:

func appendElement(s []int, val int) []int {
    s = append(s, val) // if capacity is insufficient, a new array is allocated on the heap
    return s
}

Thus, when exceeding the capacity, the slice is reallocated with a new array that is placed on the heap.

When a slice is re-declared inside a function beyond… - sobes.tech