本文介绍了如何在int之前添加切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚接触Go,因此我的问题似乎有点天真.

I am fairly new to Go and thus my question might seem a bit naive.

我有一个使用创建的切片

i have a slice which I created using

var x []int;
for i := 2; i < 10; i += 2 {
    x = append(x, i);
}

我想在此切片前添加一个整数,例如

I want to prepend an integer to this slice, something like

x = append(2, x)

但是显然它不起作用,因为append需要一个切片作为第一个参数.

but obviously it won't work since append needs a slice as the first argument.

我尝试了,但是它仅适用于字符串,不适用于我的情况.

I have tried this but it only works for strings and it's not working in my case.

推荐答案

使用切片复合文字: [] int {1} ,例如

package main

import (
    "fmt"
)

func main() {
    var x []int
    for i := 2; i < 10; i += 2 {
        x = append(x, i)
    }
    fmt.Println(x)

    x = append([]int{1}, x...)

    fmt.Println(x)
}

游乐场: https://play.golang.org/p/Yc87gO7gJlD

输出:

[2 4 6 8]
[1 2 4 6 8]


但是,这种效率更高的版本可能分配的空间更少,只有在没有备用分片容量的情况下才需要分配.


However, this more efficient version may make fewer allocations, An allocation is only necessary when there is no spare slice capacity.

package main

import (
    "fmt"
)

func main() {
    var x []int
    for i := 2; i < 10; i += 2 {
        x = append(x, i)
    }
    fmt.Println(x)

    x = append(x, 0)
    copy(x[1:], x)
    x[0] = 1

    fmt.Println(x)
}

游乐场: https://play.golang.org/p/fswXul_YfvD

输出:

[2 4 6 8]
[1 2 4 6 8]


好的代码必须可读.在Go中,我们通常将实现细节隐藏在函数内.Go编译器正在优化编译器,小型,简单的函数(例如 prependInt )已内联.

package main

import (
    "fmt"
)

func prependInt(x []int, y int) []int {
    x = append(x, 0)
    copy(x[1:], x)
    x[0] = y
    return x
}

func main() {
    var x []int
    for i := 2; i < 10; i += 2 {
        x = append(x, i)
    }
    fmt.Println(len(x), cap(x), x)

    x = prependInt(x, 1)

    fmt.Println(len(x), cap(x), x)
}

游乐场: https://play.golang.org/p/wl6gvoXraKH

输出:

4 4 [2 4 6 8]
5 8 [1 2 4 6 8]


请参见转到SliceTricks .

这篇关于如何在int之前添加切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 03:34