Senior
If I work with a slice, take it as a function parameter, do something with it, and then continue working with it after the function — what should I remember? What changes will we not see from outside?
sobes.tech AI
Answer from AI
In Go, a slice is a structure containing a pointer to an array, a length, and a capacity. When you pass a slice to a function, only this structure (pointer, length, capacity) is copied, not the array itself.
What is important to remember:
- Changes to the elements of the slice inside the function (e.g.,
s[0] = 10) will be visible outside, as they point to the same array. - Changes to the slice structure itself (e.g., assigning a new slice
s = append(s, 5)) will not affect the slice outside the function, as the structure is copied.
Example:
func modify(s []int) {
s[0] = 100 // will change the array element — visible outside
s = append(s, 200) // modifies the local copy of the slice — not visible outside
}
s := []int{1, 2, 3}
modify(s)
fmt.Println(s) // Will print [100 2 3], the addition of 200 is not reflected
In summary, changes to the elements of the slice are visible outside, but changes to the length or capacity (via append, slices) are not, unless you return a new slice or pass a pointer to the slice.