Junior — Senior
Impact of function on the passed slice
livecode
Task condition
There is a slice created with an initial capacity of 2. After adding one element 1 to it, the add() function is called with parameter 2. Question: will the changes inside the function affect the original slice?
arr := make([]int, 0, 2) // len 0 cap 2 [ , ]
arr = append(arr, 1) // len = 1 , cap = 2 [1, ]
add(arr, 2) // len = 1 , cap = 2 [1, ] → the function does not change the original slice
func add(arr []int, elem int) {
arr = append(arr, elem) // [1, 2] but this is a copy
}
The example shows that a new copy of the slice header is created inside the function, so the original array remains unchanged.