golang 內置函數append使用方式

內置函數append使用方式

看一下內置函數append在buildin.go中的註釋就知道了

// 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

註釋翻譯如下:

apeend內中函數是將元素添加到slice的末尾,如果容量足夠,目標元素被容納進切片。如果容量不足,一個新的底層數組將被分配,append函數返回結果是一個更新後的切片。因此,有必要將添加的結果存儲在通常包含切片本身的變量中。

append的使用方式:

slice = append(slice, elem)

slice = append(slice, elem1, elem2)

slice = append(slice, anotherSlice…) // 最後這三個點點點要加上,不然會報錯,這是用於兩個切片的合併的。

當然還有例外:

將string拼接到byte切片是合法的,例如

slice = append([]byte("hello "), “world”…)

請關注個人gitbook地址:https://zhounanjun.gitbook.io/nanjun/
歡迎批評指正!

發佈了159 篇原創文章 · 獲贊 141 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章