Sobes.tech
Senior

Kui ma töötan lõigu (slice)ga, võtan selle funktsiooni parameetrina, teen sellega midagi ja jätkan selle kasutamist pärast funktsiooni — millele peaksin tähelepanu pöörama? Milliseid muutusi me väljastpoolt ei näe?

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, only this structure (pointer, length, capacity) is copied, not the array itself.

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 only 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) // Prints [100 2 3], adding 200 is not reflected

In summary, changes to the slice elements are visible outside, but changes to length or capacity (via append, slices) are not, unless you return a new slice or pass a pointer to the slice.