Sobes.tech
Middle+

What is the danger of passing a slice to a function? Is there a trick with arrays?

sobes.tech AI

Answer from AI

When passing a slice to a function in Go, a slice structure is passed, not a copy of the entire array. This structure contains a pointer to the array, along with its length and capacity. This means that changes to the slice elements inside the function are reflected in the original array.

Dangers:

  • If the function modifies the slice elements, it will affect the original data.
  • If the function extends the slice (using append), and reallocation occurs (capacity increases), the new slice points to a new array, and changes no longer affect the original array.

Array nuances:

  • Arrays in Go are passed by value (copied entirely), so modifications inside the function do not affect the original.
  • Slices are wrappers over arrays, passed by value, but contain a pointer to the array.

Example:

func modifySlice(s []int) {
    s[0] = 100 // will change the original array
    s = append(s, 200) // may create a new array, not affecting the original
}

arr := []int{1, 2, 3}
modifySlice(arr)
// arr is now [100, 2, 3], but the append inside the function did not change the original slice

It is important to understand when copying occurs and when only the slice structure is copied.

What is the danger of passing a slice to a function… - sobes.tech