Middle
Can we pass a slice as a function parameter?
sobes.tech AI
Answer from AI
Yes, in Go, you can pass slices to functions as parameters. A slice in Go is a structure that contains a pointer to an array, a length, and a capacity. When passing a slice to a function, only this structure is copied, not the underlying array it points to. This means that changes to the elements of the slice inside the function will be visible outside as well, since they refer to the same array.
Example:
func modifySlice(s []int) {
s[0] = 100
}
func main() {
a := []int{1, 2, 3}
modifySlice(a)
fmt.Println(a) // Will output [100 2 3]
}
However, if you change the slice itself inside the function (for example, assign a new slice), it will not affect the original slice outside the function.