slice := []int{10, 20, 30, 40, 50,60}
newSlice := slice[2:4:5]
fmt.Printf("old slice is %d
", slice)
fmt.Printf("new slice is %d
", newSlice)
newSlice = append(newSlice,70)
fmt.Printf("old slice is %d
", slice)
fmt.Printf("new slice is %d
", newSlice)
newSlice = append(newSlice,80)
fmt.Printf("old slice is %d
", slice)
fmt.Printf("new slice is %d
", newSlice)
and the output will be
old slice is [10 20 30 40 50 60]
new slice is [30 40]
old slice is [10 20 30 40 70 60]
new slice is [30 40 70]
old slice is [10 20 30 40 70 60]
new slice is [30 40 70 80]
the append have the different behavior. I know the reason why cause the append have different behavior. Because the new and old share the array when the new slice capacity is more than length, but append 80, capacity is not big enough, so it creates a new array. So check capacity will to avoid append have different behavior or I can define the new slice newSlice := slice[2:4:4]
Is there any elegant solution? Because check before each append is a little ugly, and in some situation, I hope the old and new can share the slice all the time. How to make it happened elegant?
This is a really good source for random slice things: https://github.com/golang/go/wiki/SliceTricks
In this case, I would recommend just creating a new slice first, then appending elements every time afterwards like so:
slice := []int{10, 20, 30, 40, 50, 60}
newSlice := make([]int, 0)
newSlice = append(newSlice, slice[2:4:5]...)
fmt.Printf("old slice is %d
", slice)
fmt.Printf("new slice is %d
", newSlice)
newSlice = append(newSlice, 70)
fmt.Printf("old slice is %d
", slice)
fmt.Printf("new slice is %d
", newSlice)
newSlice = append(newSlice, 80)
fmt.Printf("old slice is %d
", slice)
fmt.Printf("new slice is %d
", newSlice)
Which results in:
old slice is [10 20 30 40 50 60]
new slice is [30 40]
old slice is [10 20 30 40 50 60]
new slice is [30 40 70]
old slice is [10 20 30 40 50 60]
new slice is [30 40 70 80]
To force allocation of a new backing array in append, use a slice with equal length and capacity. Create that slice with the three value slice expression.
newSlice = append(newSlice[:len(newSlice):len(newSlice)], 70)
As noted in the question, you can also create a slice with equal length and capacity using:
newSlice := slice[2:4:4]