I have been experimenting with slices. Here is an example program
for n := 1; n <= 10; n++ {
a := make([]int, 0)
for j := 0; j < n; j++ {
a = append(a, 0)
}
b := a[:1]
a = append(a, 0)
a[0] = 1
fmt.Println(n, b[0])
}
The output is
1 0
2 0
3 1
4 0
5 1
6 1
7 1
8 0
9 1
10 1
I understand what is going on here. The line a = append(a, 0)
allocates a new array if the old array has insufficient length, and the new array has twice the length as the original. Therefore if n
is a power of 2, the line
a[0] = 1
will not change the array backed by b
as a new array will have been allocated in the line before.
However I could not find an explicit statement in the documentation that the newly allocated array always has twice the length. Does this mean that my code is implementation dependent? Is it bad practice to store a slice of another slice in a variable in this way, or should I just do a[j:k]
every time a subslice is needed?