五分钟学会Go这个Append内建函数~

本文介绍了Go语言的内置函数append的使用,包括其工作原理和常见应用场景。通过示例展示了当追加元素超出切片容量时如何创建新数组,以及切片只感知len范围内数组内容的特点。
摘要由CSDN通过智能技术生成

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"...)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值