Sobes.tech
Senior

What happens if you pass a slice as a function argument and modify it inside?

sobes.tech AI

Answer from AI

In Go, a slice is passed to a function by value, but the slice itself is a structure containing a pointer to an array, a length, and a capacity. When passing, only this structure is copied, not the array data.

If you modify the elements of the slice inside the function (for example, assign new values by index), these changes will be visible outside because the copy of the slice points to the same underlying array.

However, if you modify the slice itself (for example, extend it using append, which may allocate a new array), this new copy with the new array will not affect the slice outside the function.

Example:

func modifySlice(s []int) {
    s[0] = 100 // will change the first element of the original array
    s = append(s, 200) // creates a new slice, but this won't affect outside
}

func main() {
    s := []int{1, 2, 3}
    modifySlice(s)
    fmt.Println(s) // Will print: [100 2 3]
}

Thus, changes to the slice elements inside the function affect the original array, but changes to the slice itself (like extension) do not.