【Go自学】一文搞懂Go append方法

我们先看一下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

 源码中定义了三种apped的使用场景:

1、为切片添加同种类型的元素

slice = append(slice, elem1, elem2)

2、将两个切片拼接到一起

slice = append(slice, anotherSlice...)

3、当切片是byte类型时,允许添加string类型的元素

slice = append([]byte("hello "), "world"...)

一、append()追加元素 

package main

import "fmt"

func main() {
	a := make([]int, 5, 10)
	for i := 0; i < len(a); i++ {
		a[i] = i
	}
	fmt.Println(a)
	a = append(a, 5,6, 7, 8, 9, 10)
	fmt.Println(a)
}

输出结果

[0 1 2 3 4]
[0 1 2 3 4 6 7 8 9 10]

 二、append()追加切片

package main

import "fmt"

func main() {
	a := make([]int, 5, 10)
	for i := 0; i < len(a); i++ {
		a[i] = i
	}
	fmt.Println(a)

	b := make([]int, 5, 10)
	for i := 5; i < len(b)+5; i++ {
		b[i-5] = i
	}
	fmt.Println(b)

	a = append(a, b...)
	fmt.Println(a)
}

 输出结果

[0 1 2 3 4]
[5 6 7 8 9]
[0 1 2 3 4 5 6 7 8 9]

根据append可以添加切片的性质,使用append可以实现删除一个切片中某一个元素或删除某一段连续元素的功能。

package main

import "fmt"

func main() {
	a := make([]int, 5, 10)
	for i := 0; i < len(a); i++ {
		a[i] = i
	}
	fmt.Println(a)

	a = append(a[:2], a[4:]...) //删除a[2],a[3]
	fmt.Println(a)
}

输出结果

[0 1 2 3 4]
[0 1 4]

三、向[]byte切片中添加string元素

package main

import "fmt"

func main() {
	a := []byte("Hello")
	fmt.Println(a, string(a))
	a = append(a, "World"...)
	fmt.Println(a, string(a))
}

输出结果

[72 101 108 108 111] Hello
[72 101 108 108 111 87 111 114 108 100] HelloWorld
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Weber77

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值