Monday, 14 January 2019

go - append to a new slice affect original slice




I have the following code which causes a weird result. I cannot understand why:



func main() {
var s = []int{2, 3}
var s1 = append(s, 4)
var a = append(s1, 5)
var b = append(s1, 6)
fmt.Println(s)
fmt.Println(s1)
fmt.Println(a)

fmt.Println(b)
}


This then results in:



[2 3]
[2 3 4]
[2 3 4 6]
[2 3 4 6]



My question is: why a is not [2 3 4 5] but [2 3 4 6]? I know append to b changes a, but how. Is this a bug because I never changed a directly and obviously I don't want this happen?


Answer



Keep in mind that a slice is a structure of 3 fields.




  • a pointer to the underlying array

  • length of the slice

  • capacity of the slice




append() function may either modify its argument in-place or return a copy of its argument with an additional entry, depending on the size and capacity of its input. append() function creates a new slice, if the length the slice is greater than the length of the array pointed by the slice.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...