Sobes.tech
Junior — Middle

Kuidas edastatakse slice funktsioonile programmeerimiskeeles?

sobes.tech AI

Vastus AI-lt

In Go, a slice is passed to a function by value, but the slice contains a pointer to an array, as well as its length and capacity. This means that when passing a slice to a function, the slice structure is copied, but not the data of the array it points to.

As a result, modifications to the elements of the slice inside the function reflect on the original array, but changing the slice itself (for example, assigning a new slice) does not affect the external slice.

Example:

package main
import "fmt"

func modifySlice(s []int) {
    s[0] = 100       // changes the element of the original array
    s = append(s, 200) // changes the local slice, the external remains unchanged
}

func main() {
    s := []int{1, 2, 3}
    modifySlice(s)
    fmt.Println(s) // Prints: [100 2 3]
}

Thus, the slice is passed by value, but thanks to the internal pointer, changes to the elements are visible outside the function.