Junior — Middle
How is a slice passed to a function in programming languages?
sobes.tech AI
Answer from AI
In Go, a slice is passed to a function by value, but only the slice structure is copied, not the entire array data. The slice structure contains a pointer to the array, its length, and capacity. This means that changes to the elements of the slice inside the function will reflect on the original array, as the pointer points to the same data.
Example:
func modifySlice(s []int) {
s[0] = 100 // will change the first element of the original slice
}
func main() {
arr := []int{1, 2, 3}
modifySlice(arr)
fmt.Println(arr) // Will output: [100 2 3]
}
Thus, passing a slice to a function is efficient and allows modifying the contents of the array it references.