If you pass a slice to a function without a pointer, will it affect the original array?
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 you pass a slice to a function without a pointer, the slice structure itself is copied, but the underlying array is not.
This means that changes to the elements of the slice inside the function will affect the original array, as both slices point to the same array. However, if you change the slice itself inside the function (for example, assign a new slice or change its length), these changes will not affect the slice outside the function.
Example:
func modifySlice(s []int) {
s[0] = 100 // will change the original array
s = append(s, 200) // will change the local slice, not the external one
}
func main() {
arr := []int{1, 2, 3}
modifySlice(arr)
fmt.Println(arr) // will print [100 2 3]
}
In summary: passing a slice without a pointer allows you to modify the elements of the original array, but does not allow you to modify the slice itself (its length, pointer) outside the function.