It's my first day in Golang, and when I try its slice operation, like append(), there is one thing that makes me so confused:
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
a:= s[2:4];
a = append(a, 1000, 1001);
a[1] = 100;
printSlice("a:", a)
printSlice("s:", s)
}
func printSlice(title string, s []int) {
fmt.Printf("%s len=%d cap=%d %v
", title, len(s), cap(s), s)
}
When I append only two numbers to a, like:
a = append(a, 1000, 1001);
...the result is:
a: len=4 cap=4 [5 100 1000 1001]
s: len=6 cap=6 [2 3 5 100 1000 1001]
Which, I think, shows a as a reference to s.
But when I change that line of code to:
a = append(a, 1000, 1001, 1002);
...the result becomes:
a: len=5 cap=8 [5 100 1000 1001 1002]
s: len=6 cap=6 [2 3 5 7 11 13]
Which, I think, a has been reassigned to another segment of memory, to hold the whole thing, and detach the reference to s.
This is so inconsistent, and makes me so confused, that sometimes it is really easy to make this error (like when you have a random number of values to append).
Why is Golang designed like this? How can this be avoided, if I just want an operation like in JavaScript's slice and push?