我跟着去学习GOLANG的旅行。
我在这一步有一个问题: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\n", len(s), cap(s), s)
}产出:
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]为什么在第二步扩展了切片的长度之后,这个切片中的值仍然是2 3 5 7?我认为这个切片中的值是0 0 0,因为我在第一步就对原始切片进行了切片。
我还有另外一个问题,为什么第三步可以改变切片的容量,而第一秒钟却不能。
发布于 2018-06-06 07:08:37
因为第一次扩展不会改变片的指针地址。因此,s还指向[2 3 5 7 11 13]地址。
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 \n", len(s), cap(s), s,(*unsafe.Pointer)(unsafe.Pointer(&s)))
}终点站显示:
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您可以看到,第三步更改了ptr地址,因为第一项被更改了。所以你知道..。
https://stackoverflow.com/questions/50713681
复制相似问题