Hello all,
I am new to Go and am going through the tour. On lesson 11/27 of MoreTypes, this is the example code (I’ve modified it to clarify my question):
package main
import "fmt"
func main() {
// Step 1: Create slice
s := []int{2, 3, 5, 7, 11, 13}
printSlice("Step 1:", s)
// Step 2: Slice the slice to give it zero length.
s = s[:0]
printSlice("Step 2:", s)
// Step 3: Extend its length.
s = s[:4]
printSlice("Step 3:", s)
// Step 4: Drop its first two values.
s = s[2:]
printSlice("Step 4:", s)
}
func printSlice(label string, s []int) {
fmt.Printf("%s len=%d cap=%d %v\n", label, len(s), cap(s), s)
}
which gives the following output:
Step 1: len=6 cap=6 [2 3 5 7 11 13]
Step 2: len=0 cap=6 []
Step 3: len=4 cap=6 [2 3 5 7]
Step 4: len=2 cap=4 [5 7]
I have read the go team blog post on slice internals to understand how slices work, and my understanding goes as follows:
- slices are abstractions on top of, or views into, arrays in memory
- a slice data structure contains 1) a pointer to somewhere in the underlying array, 2) an integer length referring to the length of the slice, and 3) an integer capacity referring to the size of the underlying array
- slices can be cropped and expanded, but arrays cannot.
So I am confused by the output of the example code. My question specifically would be “Why does the capacity of slice s change between steps 3 and 4, and not between steps 1 and 2, or between steps 2 and 3?” The output is suggesting that step 4 changes the underlying array. If this is so, why does step 4 change the underlying array and steps 2 and 3 do not?
Sorry if this question is noobish, but I am, after all, a noob. Thanks for any clarification or pointers to documentation I’ve missed.