Sobes.tech
Middle

What happens when passing a slice to a function and modifying its elements?

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, only this structure (pointer, length, capacity) is copied, not the array itself.

This means that inside the function, the slice points to the same underlying array as outside. Therefore, modifying the elements of the slice inside the function will change the elements of the original array.

Example:

func modify(slice []int) {
    slice[0] = 100
}

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

However, if inside the function you change the slice itself (for example, slice = append(slice, 4)), this will not affect the slice outside, because only the structure of the slice is copied, not the reference to it.

What happens when passing a slice to a function and… - sobes.tech