877 viewsAsked at 4 companies
What is the difference between passing an entire array and passing its slice to a function?
AI answer
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.
Also asked at OZON
Similar questions
- What are the differences when passing a slice array to a function by reference and by value?
- What will happen to the slice when passing it to a function, adding an element, and modifying an existing one?
- If you pass a slice to a function without a pointer, will it affect the original array?
- How are function parameters passed in Go, particularly slices?
- If we pass a large array (for example, size of a megabyte) to a function, is it passed by reference automatically or not?