golang-101-hacks(9)——追加元素

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

内容简介:注:本文是对在Slice中添加元素:可以使用“Go”内置函数

注:本文是对 golang-101-hacks 中文翻译。

在Slice中添加元素:可以使用“Go”内置函数 append

Go has a built-in append function which add elements in the slice:

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

但是如果需要增加到最前面,可以使用copy函数,如下

But how if we want to the "prepend" effect? Maybe we should use copy function. E.g.:

package main

import "fmt"

func main()  {
    var s []int = []int{1, 2}
    fmt.Println(s)

    s1 := make([]int, len(s) + 1)
    s1[0] = 0
    copy(s1[1:], s)
    s = s1
    fmt.Println(s)

}

运行结果

The result is like this:

[1 2]
[0 1 2]

上面的代码看上去不是很完美,一种友好的写法如下

But the above code looks ugly and cumbersome, so an elegant implementation maybe here:

s = append([]int{0}, s...)

顺便补充一点,我尝试写了一个通用的前置增加函数

BTW, I also have tried to write a "general-purpose" prepend:

func Prepend(v interface{}, slice []interface{}) []interface{}{
    return append([]interface{}{v}, slice...)
}

但是由于 []T 不能直接转换成 []interface{} (请参考 https://golang.org/doc/faq#convert_slice_of_interface ,因此也就是玩玩啦,没什么实际意义。

But since []T can't convert to an []interface{} directly (please refer https://golang.org/doc/faq#convert_slice_of_interface , it is just a toy, not useful.

参考::

Go – append/prepend item into slice .


以上所述就是小编给大家介绍的《golang-101-hacks(9)——追加元素》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

妙趣横生的算法

妙趣横生的算法

杨峰 / 清华大学出版社 / 2010-4 / 49.00元

《妙趣横生的算法(C语言实现)》理论与实践相结合,旨在帮助读者理解算法,并提高C语言编程能力,培养读者的编程兴趣,并巩固已有的C语言知识。全书分为2个部分共10章,内容涵盖了编程必备的基础知识(如数据结构、常用算法等),编程实例介绍,常见算法和数据结构面试题等。《妙趣横生的算法(C语言实现)》最大的特色在于实例丰富,题材新颖有趣,实用性强,理论寓于实践之中。通过《妙趣横生的算法(C语言实现)》的学......一起来看看 《妙趣横生的算法》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具