Senior
What will the code with slices and passing to a function output? How does passing a slice to a function work?
sobes.tech AI
Answer from AI
In Go, slices are passed to functions by value, but only the slice structure (pointer to the array, length, capacity) is copied, not the underlying array itself. This means that changes to the elements of the slice inside the function are reflected in the original array.
Example:
func modify(slice []int) {
slice[0] = 100
slice = append(slice, 200) // modifies the local slice, the original remains unchanged
}
func main() {
s := []int{1, 2, 3}
modify(s)
fmt.Println(s) // Will output: [100 2 3]
}
Explanation:
slice[0] = 100changes the element in the original array.appendmay create a new array if capacity is insufficient, but this does not affect the original slice inmain.
Thus, passing a slice allows modifying the contents of the array, but not the slice structure itself (such as length) outside the function.