小编典典

在Go中串联两个切片

go

我正在尝试将切片[1, 2]和切片结合起来[3, 4]。如何在Go中执行此操作?

我试过了:

append([]int{1,2}, []int{3,4})

但得到:

cannot use []int literal (type []int) as type int in append

但是,文档似乎表明这是可能的,我想念的是什么?

slice = append(slice, anotherSlice...)

阅读 310

收藏
2020-07-02

共1个答案

小编典典

在第二个切片之后添加点:

//---------------------------vvv
append([]int{1,2}, []int{3,4}...)

就像任何其他可变参数函数一样。

func foo(is ...int) {
    for i := 0; i < len(is); i++ {
        fmt.Println(is[i])
    }
}

func main() {
    foo([]int{9,8,7,6,5}...)
}
2020-07-02