// The append built-in function appends elements to the end of a slice. If
// it has sufficient capacity, the destination is resliced to accommodate the
// new elements. If it does not, a new underlying array will be allocated.
// Append returns the updated slice. It is therefore necessary to store the
// result of append, often in the variable holding the slice itself:
// slice = append(slice, elem1, elem2)
// slice = append(slice, anotherSlice...)
// As a special case, it is legal to append a string to a byte slice, like this:
// slice = append([]byte("hello "), "world"...)
func append(slice []Type, elems ...Type) []Type
append对一个切片类型进行追加,并返回切片类型。追加的时候是直接操作的内存,有一些坑需要注意。
slice具有两个属性,len和cap,当cap不够的时候,会重新分配内存,slice指针的值也会发生改变。
如代码所示,我本想通过append函数往slice1里面插入999,结果发现在第一次append(slice1[:3], 999)之后直接将slice1[3]的值改成了999,后面再取slice1[3:]的时候就变成了{999, 5},所以最后slice1变成了{1, 2, 3, 999, 999, 5}。
当我对slice2进行append(slice2[:3], 999, 888, 777)之后,原slice2分配的cap不够存放,即重新分配内存返回新的临时slice地址,那么再取之前的slice2的时候,slice2[3]就没有被改变,4没有被覆盖掉。
slice1 := []int{1, 2, 3, 4, 5}
slice1 = append(append(slice1[:3], 999), slice1[3:]...)
for i := range slice1 {
fmt.Printf("%d ", slice1[i])
}
println()
// 1 2 3 999 999 5
slice2 := []int{1, 2, 3, 4, 5}
slice2 = append(append(slice2[:3], 999, 888, 777), slice2[3:]...)
for i := range slice2 {
fmt.Printf("%d ", slice2[i])
}
println()
// 1 2 3 999 888 777 4 5