Can we pass a slice as a parameter to a function? Are there any nuances in such passing?
sobes.tech AI
Answer from AI
Yes, in Go, you can pass a slice as a function parameter. It is important to understand that a slice is a structure containing a pointer to an array, a length, and a capacity.
When passing a slice to a function, only this structure (header) is copied, not the entire data array. Therefore, inside the function, you can modify the array elements through the slice, and these changes will be visible outside.
However, if you modify the slice itself inside the function (for example, by using append, which allocates a new array), this new version of the slice will not affect the slice outside the function, as only the slice structure is copied.
Example:
func modifySlice(s []int) {
s[0] = 100 // will change the first element of the original array
s = append(s, 200) // creates a new slice, but does not change the external one
}
func main() {
s := []int{1, 2, 3}
modifySlice(s)
fmt.Println(s) // Will output: [100 2 3]
}
If you want changes to the slice (for example, extension) to be visible outside, you can pass a pointer to the slice:
func modifySlicePtr(s *[]int) {
*s = append(*s, 200) // will modify the slice outside
}
func main() {
s := []int{1, 2, 3}
modifySlicePtr(&s)
fmt.Println(s) // Will output: [1 2 3 200]
}
In summary:
- Changes to slice elements inside the function are visible outside.
- Changes to the slice structure (length, capacity) without passing a pointer are not visible outside.
- To modify the length of a slice outside, pass a pointer to the slice.