Hi folk,
I am tring to understand below code snippet .
When trace the output , logically output is different than actual go compiler.
Could you please explain why go compiler give different output ?
what will be output of below code & explain why
a := int{0, 1, 2, 3}
x := a[:1] //0
y := a[2:] //2,3
x = append(x, y…) //0,2,3
x = append(x, y…) //0,2,3,2,3
fmt.Println(a, x) //0,1,2,3, 0,2,3,2,3
}
//actual o/p => 0 2 3 3] [0 2 3 3 3]
lemarkar
(Leo Emar-Kar)
January 14, 2025, 2:24pm
2
Can you be more specific what causes difficulty? Because right now everything looks as it suppose to be.
“Changing the elements of a slice modifies the corresponding elements of its underlying array ”
See for example Slices are like references to arrays
Here, the first append changes a to [0, 2, 3, 3] and therefore y to [3,3]
1 Like
Thanks for your reply,
What happen at append(in above example), how it will change the value.
Could you please elaborate given above example.
Have a look at Go Slices: usage and internals :
Here slice x has a pointer to array a at position 0, with length 1.
Appending y to x overwrites the underlying array a from position 1.
And, since y is a slice into a at position 2, it sees the changes as well.
Just print a and y after the append.
Be aware with slices and arrays. If you append something to y which exceeds the capacity of a it allocates new memory and does not change a
1 Like