I follow the tour of Go to learning GOLANG.
And I have a question at this step: https://tour.golang.org/moretypes/11
package main
import "fmt"
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Step1 Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Step2 Extend its length.
// Why after extend the length of the slice, the value in this slice is still [2 3 5 7]
s = s[:4]
printSlice(s)
// Step 3 Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v
", len(s), cap(s), s)
}
The output:
len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [2 3 5 7]
len=2 cap=4 [5 7]
Why after extending the length of the slice at the second step, the value in this slice is still [2 3 5 7]? I think the value in this slice is [0 0 0 0] because I have sliced the origin slice at the first step.
And I have another question is that why the third step can change the capacity of the slice but the first second cannot.
Because the first time extending does not change the slice's pointer address. So s
also points to the [2 3 5 7 11 13]
address.
package main
import (
"fmt"
"unsafe"
)
func main() {
s := []int{2, 3, 5, 7, 11, 13}
printSlice(s)
// Slice the slice to give it zero length.
s = s[:0]
printSlice(s)
// Extend its length.
s = s[:4]
printSlice(s)
// Drop its first two values.
s = s[2:]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v array ptr: %v
", len(s), cap(s), s,(*unsafe.Pointer)(unsafe.Pointer(&s)))
}
the terminal shows:
len=6 cap=6 [2 3 5 7 11 13] array ptr: 0xc04200a2a0
len=0 cap=6 [] array ptr: 0xc04200a2a0
len=4 cap=6 [2 3 5 7] array ptr: 0xc04200a2a0
len=2 cap=4 [5 7] array ptr: 0xc04200a2b0
you see, the third step changes the ptr
address because of first item is changed. so you know...