Sobes.tech
Junior — Middle

What data is passed inside a slice when calling a function with this slice as an argument?

sobes.tech AI

Answer from AI

In Go, a slice is a structure that contains three fields: a pointer to an array, a length, and a capacity. When passing a slice to a function, only this structure is copied, not the entire data array.

This means that when a function is called with a slice, it is passed by value, but only the metadata (pointer, length, capacity) is copied, not the array elements themselves. This implies that inside the function, the slice points to the same underlying array, and modifications to the slice elements inside the function will be visible outside.

Example:

func modify(slice []int) {
    slice[0] = 100 // change the first element
}

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

Thus, when passing a slice to a function, only the three fields of the slice structure are copied, while the array data remains shared.

What data is passed inside a slice when calling a… - sobes.tech