append
append是golang中的一个内建函数,它的作用是官方的介绍是
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.
append 内置函数将元素追加到切片的末尾。如果它有足够的容量,则重新切片容纳新元素。如果没有,将分配一个新的底层数组,并且 Append 返回更新后的新的切片。因此有必要存储追加的结果,通常会保存原切片中。
定义:
func append(slice []Type, elems ...Type) []Type
用法:
slice = append(slice, elem1, elem2) slice = append(slice, anotherSlice...)
特别地,将字符串附加到字节切片是合法的:
slice = append([]byte("hello "), "world"...)

本文介绍了Go语言的内置函数append的使用,包括其工作原理和常见应用场景。通过示例展示了当追加元素超出切片容量时如何创建新数组,以及切片只感知len范围内数组内容的特点。
最低0.47元/天 解锁文章
1149

被折叠的 条评论
为什么被折叠?



