【发布时间】:2018-06-06 06:35:59
【问题描述】:
我跟着 Go 的导览学习 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 0] 因为我在第一步已经切片了原点切片。
还有一个问题是为什么第三步可以改变切片的容量,而第一秒却不能。
【问题讨论】:
-
@mkopriva Slice internals 零件可以很好地回答我的问题。 1. slice 是数组段的描述符。 2.容量是底层数组中元素的数量(从切片指针引用的元素开始)。谢谢
-
解释到一定程度a couple pages early in the Tour。切片和重新切片仍然给您留下相同的底层数组,并且该数组中的值没有改变,因此没有理由期望切片中的值(这只是该数组的视图)会改变。
标签: go