Senior
Will the array res be on the stack or on the heap, considering that it is passed to the functions double and append?
sobes.tech AI
Answer from AI
In Go, arrays are values of fixed size and are usually located where they are declared. If an array is declared within a function, it will be placed on the stack. When passing an array to a function, the entire array is copied (value copy), meaning a new array is created on the stack of the called function.
However, when passing a slice, a structure with a pointer to data in the heap, along with length and capacity, is passed, and the data itself may reside in the heap.
Example:
func double(arr [3]int) {
for i := range arr {
arr[i] *= 2
}
func append(arr []int, val int) []int {
return append(arr, val)
}
func main() {
res := [3]int{1, 2, 3} // array on the main stack
double(res) // copy of array on the stack in double
slice := []int{1, 2, 3} // slice, data in the heap
slice = append(slice, 4) // possibly allocates new memory in the heap
}
In summary: arrays are passed by value, copied onto the caller's stack. Slices are structures with a pointer to data in the heap.