slice的属性 切片(slice)是建立在数组之上的更方便,更灵活,更强大的数据结构。切片并不存储任何元素而只是对现有数组的引用。 切片的长度是指切片中元素的个数。切片的容量是指从切片的起始元素开始到其底层数组中的最后一个元素的个数。 那么问题来了,几个不同的切片指向同一个数组,如果数组的值被改变会出现什么神奇的操作? 问题实例 slice的cap是怎么增长的 参考文章:How does Go slice capacity change on append? [duplicate] 有兴趣也可以看看golang的源码实现,在$GOPATH/src/runtime/slice.go slice的结构 1 2 3 4 5 6 7 8 9 10 11 type slice struct { array unsafe.Pointer len int cap int } 多次append造成的数据错误 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package main import "fmt" func main() { temp := []int{} temp = append(temp, 1) printSlice("temp", temp) temp = append(temp, 2) printSlice("temp", temp) temp = append(temp, 3) // temp := []int{1, 2, 3} printSlice("temp", temp) temp2 := append(temp, 4) printSlice("temp2", temp2) temp4 := append(temp, 5, 6) printSlice("temp4", temp4) temp3 := append(temp, 5) printSlice("temp3", temp3) printSlice("temp2", temp2) } func printSlice(valName string, s []int) { fmt.……

阅读全文