Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

In Go, when passing an array to a function, the entire array is copied, meaning a full copy is created. This can be costly in terms of memory and time, especially for large arrays. Changes inside the function do not affect the original array.

When passing a slice, a slice structure (pointer to the array, length, and capacity) is passed by value, but the pointer points to the original array. Therefore, changes to the slice elements inside the function are reflected in the original array, and only a small slice structure is copied, which is more efficient.

Example:

func modifyArray(a [3]int) {
    a[0] = 10 // only the copy will change
}

func modifySlice(s []int) {
    s[0] = 10 // the original array will change
}

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

    slice := arr[:]
    modifySlice(slice)
    fmt.Println(arr) // [10 2 3]
}

Thus, slices are more convenient and efficient for passing large data sets and allow modifying the original data inside functions.

What is the difference between passing an entire… - sobes.tech