Junior — Middle
Milliseid andmeid sisemiselt slice'is edastatakse funktsiooni kutsumisel selle slice'iga argumentina?
sobes.tech AI
Vastus AI-lt
In Go, a slice is a structure that contains three fields: a pointer to an array, a length, and a capacity. When a slice is passed to a function, only this structure is copied, not the entire data array.
That is, when calling a function, the slice is passed by value, but only the metadata (pointer, length, capacity) is copied, not the elements of the array itself. This means that inside the function, the slice points to the same underlying array, and changes 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 print [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.