Senior
// what will be printed on each print? func fn(a []int) { a[2] = 5 a = append(a, 6) fmt.Println(a) // a = append(a, 7) a[0] = 5 fmt.Println(a) // } func main() { a := make([]int, 0, 5) for i := 0; i < 4; i++ { a = append(a, i) } fn(a[:3]) fmt.Println(a) // }
sobes.tech AI
Answer from AI
Let's analyze the code step by step:
func fn(a []int) {
a[2] = 5
a = append(a, 6)
fmt.Println(a) // 1st print
a = append(a, 7)
a[0] = 5
fmt.Println(a) // 2nd print
}
func main() {
a := make([]int, 0, 5)
for i := 0; i < 4; i++ {
a = append(a, i)
}
fn(a[:3])
fmt.Println(a) // 3rd print
}
- In main, a slice
ais created with length 4 and capacity 5:[0,1,2,3]. - The call
fn(a[:3])passes a slice of the first three elements:[0,1,2].
Inside fn:
a[2] = 5changes the third element from 2 to 5, soainside the function becomes[0,1,5].a = append(a, 6)adds 6. The capacity was 5, length 3, so appending does not cause reallocation, and the slice extends to[0,1,5,6], referencing the same underlying array as the original slice.- The first
fmt.Println(a)outputs:[0 1 5 6].
Next:
a = append(a, 7)adds 7. Now length is 5, capacity 5, so appending causes a new array to be allocated, data copied, andainside the function now points to this new array:[0,1,5,6,7].a[0] = 5changes the first element to 5, soainside the function becomes[5,1,5,6,7].- The second
fmt.Println(a)outputs:[5 1 5 6 7].
After the function exits:
- The slice
ain main remains unchanged after the first append because the second append inside the function created a new array. - But
a[2]was changed to 5 (because the first append did not create a new array, and changes reflect on the original array).
The third fmt.Println(a) outputs: [0 1 5 3].
Summary:
[0 1 5 6]
[5 1 5 6 7]
[0 1 5 3]
Explanation:
- The first append does not cause copying; changes reflect on the original array.
- The second append causes copying; changes after it do not affect the original slice.
- Changing
a[2]before the first append modifies the original array. - Changing
a[0]after the second append affects only the local slice inside the function.