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]

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

查看所有标签

猜你喜欢:

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

Introduction to Graph Theory

Introduction to Graph Theory

Douglas B. West / Prentice Hall / 2000-9-1 / USD 140.00

For undergraduate or graduate courses in Graph Theory in departments of mathematics or computer science. This text offers a comprehensive and coherent introduction to the fundamental topics of graph ......一起来看看 《Introduction to Graph Theory》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试