drake900918 2018-12-12 06:43
浏览 72
已采纳

如何在切片前添加int

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)

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.

  • 写回答

1条回答 默认 最新

  • drzdu44226 2018-12-12 06:58
    关注

    Use a slice composite literal: []int{1}, For example,

    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)
    }
    

    Playground: https://play.golang.org/p/Yc87gO7gJlD

    Output:

    [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)
    }
    

    Playground: https://play.golang.org/p/fswXul_YfvD

    Output:

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

    Good code must be readable. In Go, we often hide implementaion details inside a function. Go compilers are optimizing compilers, small, simple functions (like prependInt) are inlined.

    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)
    }
    

    Playground: https://play.golang.org/p/wl6gvoXraKH

    Output:

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

    See Go SliceTricks.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统