当前位置: 首页 > news >正文

【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 mainimport "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 mainimport "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 mainimport "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 mainimport "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
http://www.lryc.cn/news/56298.html

相关文章:

  • 【压测】通过Jemeter进行压力测试(超详细)
  • C# | 上位机开发新手指南(七)加密算法
  • 实验一 跨VLAN访问
  • 通信算法之130:软件无线电-接收机架构
  • C++编程大师之路:从入门到精通-C++基础入门
  • 如何在千万级数据中查询 10W 的数据并排序
  • RocketMQ消息文件过期原理
  • Docker容器理解
  • SpringBoot 整合knife4j
  • 73-归并排序练习-LeetCode148排序链表
  • Hystrix学习笔记
  • 面向对象编程(基础)8:关键字:package、import
  • 【机器学习】P10 从头到尾实现一个线性回归案例
  • 【Java EE】-多线程编程(四) 死锁
  • 学习数据结构第1天(数据结构的基本概念)
  • 南大通用数据库-Gbase-8a-学习-33-空洞率查询与解决方法
  • 为什么我们认为GPT是一个技术爆炸
  • 程序员如何能提高自己的编程水平?
  • 从零使用vuepress搭建个人博客部署.github.io
  • Python 进阶指南(编程轻松进阶):十一、注释、文档字符串和类型提示
  • python item()方法
  • 【day2】Android Jetpack Compose环境搭建
  • stable-diffusion安装和简单测试
  • MATLAB算法实战应用案例精讲-【智能优化算法】 基于帕累托包络的选择算法II(PESA-II)(附MATLAB代码实现)
  • 【华为机试真题详解JAVA实现】—坐标移动
  • 【软考五】数据库(做题)
  • 【Java Web】012 -- SpringBootWeb综合案例(登录功能、登录校验、异常处理)
  • 跨界智能手表:比亚迪向左,小鹏向右
  • 【c++初阶】第九篇:vector(常用接口的使用 + 模拟实现)
  • Taro React组件使用(6) —— RuiSendCode 短信验证码【倒计时】