Sobes.tech
Middle+

What is the difference between passing a slice and an array to a function?

sobes.tech AI

Answer from AI

In Go, arrays and slices are passed to functions differently:

  • Arrays are passed by value, meaning they are copied entirely. Changes inside the function do not affect the original array.
  • Slices are a structure containing a pointer to an array, a length, and a capacity. When passing a slice, only this structure (24 bytes) is copied, but it points to the same underlying array. Therefore, changes to slice elements inside the function are reflected in the original data.

Example:

func modifyArray(arr [3]int) {
    arr[0] = 100
}

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

func main() {
    a := [3]int{1, 2, 3}
    modifyArray(a)
    fmt.Println(a) // [1 2 3] - unchanged

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

Thus, slices are more convenient for passing large datasets when you need to modify the contents, while arrays are suitable when a copy is needed.