Junior — Middle
How is a slice passed to a function in a programming language?
sobes.tech AI
Answer from AI
In Go, a slice is passed to a function by value, but the slice contains a pointer to an array, along with its length and capacity. This means that when passing a slice to a function, the slice structure is copied, but the underlying array data it points to is not copied.
As a result, modifications to the elements of the slice inside the function are reflected in the original array, but changes to the slice itself (for example, assigning a new slice) do not affect the external slice.
Example:
package main
import "fmt"
func modifySlice(s []int) {
s[0] = 100 // will change the element in the original array
s = append(s, 200) // will change the local slice, but not the external one
}
func main() {
s := []int{1, 2, 3}
modifySlice(s)
fmt.Println(s) // Will output: [100 2 3]
}
Thus, a slice is passed by value, but due to the internal pointer, changes to elements are visible outside the function.