Sobes.tech
Junior — Middle

Is it possible to modify the contents of an array passed as a slice during program execution?

sobes.tech AI

Answer from AI

Yes, the contents of the array passed as a slice can be modified during program execution. A slice in Go is a structure that contains a pointer to an array, a length, and a capacity. Changes to the elements of the slice are reflected in the original array, as the slice points to its data.

Example:

package main
import "fmt"

func modifySlice(s []int) {
    s[0] = 100
}

func main() {
    arr := [3]int{1, 2, 3}
    slice := arr[:]
    modifySlice(slice)
    fmt.Println(arr) // Will output: [100 2 3]
}

Thus, modifying the slice also modifies the original array.