Go语言的append操作

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

append对一个切片类型进行追加,并返回切片类型。追加的时候是直接操作的内存,有一些坑需要注意。

slice具有两个属性,len和cap,当cap不够的时候,会重新分配内存,slice指针的值也会发生改变。

如代码所示,我本想通过append函数往slice1里面插入999,结果发现在第一次append(slice1[:3], 999)之后直接将slice1[3]的值改成了999,后面再取slice1[3:]的时候就变成了{999, 5},所以最后slice1变成了{1, 2, 3, 999, 999, 5}。

当我对slice2进行append(slice2[:3], 999, 888, 777)之后,原slice2分配的cap不够存放,即重新分配内存返回新的临时slice地址,那么再取之前的slice2的时候,slice2[3]就没有被改变,4没有被覆盖掉。

slice1 := []int{1, 2, 3, 4, 5}
slice1 = append(append(slice1[:3], 999), slice1[3:]...)
for i := range slice1 {
	fmt.Printf("%d ", slice1[i])
}
println()
// 1 2 3 999 999 5

slice2 := []int{1, 2, 3, 4, 5}
slice2 = append(append(slice2[:3], 999, 888, 777), slice2[3:]...)
for i := range slice2 {
	fmt.Printf("%d ", slice2[i])
}
println()
// 1 2 3 999 888 777 4 5

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值