小编典典

在 Go 中连接两个slice

go

我正在尝试将 slice[1, 2]和 slice结合起来[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...)

阅读 189

收藏
2021-10-24

共1个答案

小编典典

在第二个 slice后添加点:

//---------------------------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}...)
}
2021-10-24