Kas mõjutab algset massiivi, kui edastada funktsioonile koopia ilma näitajata?
sobes.tech AI
Vastus AI-lt
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 modifications to the elements of the slice inside the function will affect the original array, since both slices point to the same array. However, if you modify the slice itself (for example, assigning it a new slice or changing its length), these changes will not affect the slice outside the function.
Example:
func modifySlice(s []int) {
s[0] = 100 // will modify the original array
s = append(s, 200) // will modify the local slice, not affecting the external
}
func main() {
arr := []int{1, 2, 3}
modifySlice(arr)
fmt.Println(arr) // Prints [100 2 3]
}
Summary: passing a slice without a pointer allows modifying the elements of the original array, but does not allow changing the slice itself (its length, pointer) outside the function.