slice := []int{1, 2, 3} newSlice := slice[0:2] //这个地方是关键 fmt.Printf("before the origin slice address=%p \n", slice) fmt.Printf("before the new slice address=%p \n", slice) fmt.Println("before the origin slice data = ", slice) fmt.Println("before the new slice data = ", newSlice) newSlice = append(newSlice, 4) fmt.Println("after append the new slice data = ", newSlice) // 并不会改变原来数组的值 for _, v := range newSlice { v += 10 } fmt.Println("after first change the new slice data = ", newSlice)
// 会改变slice和newSlice的值 for i := range newSlice { newSlice[i] += 10 }
fmt.Printf("after the origin slice address=%p \n", slice) fmt.Printf("after the new slice address=%p \n", newSlice) fmt.Println("after second change the new slice data = ", newSlice) fmt.Println("after second change the origin slice data = ", slice)
before the origin slice address=0xc000090000 before the new slice address=0xc000090000 before the origin slice data = [1 2 3] before the new slice data = [1 2] after append the new slice data = [1 2 4] after first change the new slice data = [1 2 4] after the origin slice address=0xc000090000 after the new slice address=0xc000090000 after second change the new slice data = [11 12 14] after second change the origin slice data = [11 12 14]
slice := []int{1, 2, 3} newSlice := slice[1:] // 相比上一个代码,把slice[0:2]修改了slice[1:] fmt.Printf("before the origin slice address=%p \n", slice) fmt.Printf("before the new slice address=%p \n", slice) fmt.Println("before the origin slice data = ", slice) fmt.Println("before the new slice data = ", newSlice) newSlice = append(newSlice, 4) fmt.Println("after append the new slice data = ", newSlice) // 并不会改变原来数组的值 for _, v := range newSlice { v += 10 } fmt.Println("after first change the new slice data = ", newSlice)
// 会改变slice和newSlice的值 for i := range newSlice { newSlice[i] += 10 }
fmt.Printf("after the origin slice address=%p \n", slice) fmt.Printf("after the new slice address=%p \n", newSlice) fmt.Println("after second change the new slice data = ", newSlice) fmt.Println("after second change the origin slice data = ", slice)
before the origin slice address=0xc00008a000 before the new slice address=0xc00008a000 before the origin slice data = [1 2 3] before the new slice data = [2 3] after append the new slice data = [2 3 4] after first change the new slice data = [2 3 4] after the origin slice address=0xc00008a000 after the new slice address=0xc00008a040 after second change the new slice data = [12 13 14] after second change the origin slice data = [1 2 3]