Go 语言中如果将元素插入到 slice 前面

栏目: Go · 发布时间: 7年前

内容简介:一次代码实现中,需要在将元素插入到我们知道,在 Go 语言中,可用注意,

一次代码实现中,需要在将元素插入到 slice 的第一位,是否有标准库来实现?

我们知道,在 Go 语言中,可用 append 来将元素附加到 slice 的后面,比如:

slice := []int{1, 2, 3}  
slice = append(slice, 4)  
// 输出:[1 2 3 4]

注意, append 函数不仅可以插入一个元素,还可以同时插入多个元素,即:

slice := []int{1, 2, 3}  
slice = append(slice, 4, 5, 6)  
// 输出:[1 2 3 4 5 6]

这就要看下 append 的函数体了(在 buildin.go 中):

func append(slice []Type, elems ...Type) []Type

append 是 Go 中的内置函数,其作用就是在 slice 的尾部插入若干元素。

回到我开头的需求,如果将元素插入到 slice 的首部呢?有一个讨巧的方法, 只需要调换两个参数的位置即可 :

slice := []int{1, 2, 3}  
// 将元素4,5,6插入到slice的前面
slice = append([]{4, 5, 6}, slice...)  
// 输出:[4 5 6 1 2 3]

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Web Applications (Hacking Exposed)

Web Applications (Hacking Exposed)

Joel Scambray、Mike Shema / McGraw-Hill Osborne Media / 2002-06-19 / USD 49.99

Get in-depth coverage of Web application platforms and their vulnerabilities, presented the same popular format as the international bestseller, Hacking Exposed. Covering hacking scenarios across diff......一起来看看 《Web Applications (Hacking Exposed)》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具