将两个slice合并到一个总的slice过程中使用copy
v1Slice := []int{1, 2}
totalSlice := []int{}
c := copy(totalSlice, v1Slice)
fmt.Printf("c:%v\ntotalSlice:%+v\n", c, totalSlice)
v2Slice := []int{3, 4}
totalSlice = append(totalSlice, v2Slice...)
fmt.Printf("\nv1Slice:%+v\n", v1Slice)
fmt.Printf("\nv2Slice:%+v\n", v2Slice)
fmt.Printf("\ntotalSlice:%+v\n", totalSlice)
输出:
c:0
totalSlice:[]
v1Slice:[1 2]
v2Slice:[3 4]
totalSlice:[3 4]
发现这个有问题,不是自己想要的:
代码修改为:
v1Slice := []int{1, 2}
totalSlice := make([]int, len(v1Slice))
c := copy(totalSlice, v1Slice)
fmt.Printf("c:%v\ntotalSlice:%+v\n", c, totalSlice)
v2Slice := []int{3, 4}
totalSlice = append(totalSlice, v2Slice...)
fmt.Printf("\nv1Slice:%+v\n", v1Slice)
fmt.Printf("\nv2Slice:%+v\n", v2Slice)
fmt.Printf("\ntotalSlice:%+v\n", totalSlice)
输出:
c:2
totalSlice:[1 2]
v1Slice:[1 2]
v2Slice:[3 4]
totalSlice:[1 2 3 4]
发现copy会copy目标slice元素的个数。所以 totalSlice := make([]int, len(v1Slice)),totalSlice 用make指定slice的长度。
有疑问加站长微信联系(非本文作者)