Golang append() 切片 追加 切片

Golang append() 切片 追加 切片


a := [...]int{1, 2, 3}
b := [...]int{9, 8, 7}
a = append(a, b)

会遇到 Cannot use 'b' (type []int) as type int 的问题。



将第三行append语句改为 append(a, b...) 即可。注意那三个点


func append(slice []Type, elems ...Type) []Type
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"...)

我们知道 append 函数有两种用法:
1. append(slice, elem1, elem2) append(原切片, 元素1, 元素2)
2. append(slice, anotherSlice...) append(原切片, 另一个切片 ...) 这三个点就很有魔性了,它的作用是把原切片打散,然后分别当做参数传入形参中。