Golang append() 切片 追加 切片

发布于 4 天前  3 次阅读


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...) 即可。注意那三个点

根据官方文档:

Package:
builtin
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(原切片, 另一个切片 ...) 这三个点就很有魔性了,它的作用是把原切片打散,然后分别当做参数传入形参中。


无聊的并不是这段时光,而是与别人相似的自己。