Junior — Middle
What are the differences when passing a slice array to a function by reference and by value?
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 passing a slice to a function by value, this structure—meaning the pointer, length, and capacity—is copied, but not the underlying array itself.
Passing by value:
- The slice structure (pointer, length, capacity) is copied.
- Changes to array elements inside the function affect the original array, since the pointer points to the same array.
- Changes to the slice's length or capacity inside the function do not affect the slice outside the function.
Passing by reference (pointer to a slice):
- A pointer to the slice structure is passed.
- You can modify not only the array elements but also the slice structure itself (for example, changing length, capacity, or pointing to another array).
- Changes to the slice structure inside the function will be visible outside.
Example:
func modifySlice(s []int) {
s[0] = 100 // modifies the element of the original array
s = append(s, 200) // modifies the local copy of the slice, does not affect the external slice
}
func modifySlicePtr(s *[]int) {
(*s)[0] = 100
*s = append(*s, 200) // modifies the external slice
}
func main() {
s := []int{1, 2, 3}
modifySlice(s)
fmt.Println(s) // [100 2 3]
modifySlicePtr(&s)
fmt.Println(s) // [100 2 3 200]
}
Thus, if you need to change the length or capacity of a slice inside a function and want the changes to be visible outside, pass a pointer to the slice. If only modifying elements is sufficient, you can pass the slice by value.