append用來將元素添加到切片末尾並返回結果。
看代碼:
package main import "fmt" func main() { x := []int {1,2,3} y := []int {4,5,6} //注意下面這兩個區別 fmt.Println(append(x,4,5,6)) fmt.Println(append(x,y...)); }
輸出結果:
[1 2 3 4 5 6]
[1 2 3 4 5 6]
append的用法有兩種:
slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)
第一種用法中,第一個參數為slice,后面可以添加多個參數。
如果是將兩個slice拼接在一起,則需要使用第二種用法,在第二個slice的名稱后面加三個點,而且這時候append只支持兩個參數,不支持任意個數的參數。
