Describe how to use pointers with arrays and slices in Go. What are the key differences in behavior?

Go & Rust interview question for Advanced practice.

Answer

In Go, arrays are value types, while slices are reference types. This fundamental difference dictates how pointers interact with them. Pointers and Arrays: Because arrays are value types, when you pass an array to a function, a full copy of the array's data is made. To modify the original array within a function, you must explicitly pass a pointer to the array (e.g., func modify(arr [5]int)). This avoids the expensive copy and allows for in-place modification. Pointers and Slices: A slice is a small header that contains a pointer to an underlying array, a length, and a capacity. When you pass a slice to a function, this header is copied, but the pointer inside it still points to the same underlying array. Therefore, if the function modifies the elements of the slice, the changes will be visible to the caller without needing to explicitly pass a pointer to the slice itself. You only need to pass a pointer to a slice ([]T) if the function itself needs to modify the slice header (e.g., to append elements and potentially change its length and capacity).

Explanation

A slice header itself is a small struct-like object containing a pointer to the underlying array, a length, and a capacity. This is why passing a slice is cheap.

Related Questions