在Go中连接两个切片 [英] Concatenate two slices in Go
本文介绍了在Go中连接两个切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图合并切片 [1,2]
和切片 [3,4]
。如何在Go中执行此操作?
I'm trying to combine the slice [1, 2]
and the slice [3, 4]
. How can I do this in Go?
我试过了:
I tried:
append([]int{1,2}, []int{3,4})
但得到:
but got:
cannot use []int literal (type []int) as type int in append
但是,文档似乎表明这是可能的,我错过了什么?
However, the documentation seems to indicate this is possible, what am I missing?
slice = append(slice, anotherSlice...)
推荐答案
在第二个切片后添加点:
Add dots after the second slice:
//---------------------------vvv
append([]int{1,2}, []int{3,4}...)
这就像任何其他可变参数函数一样。
This is just like any other variadic function.
func foo(is ...int) {
for i := 0; i < len(is); i++ {
fmt.Println(is[i])
}
}
func main() {
foo([]int{9,8,7,6,5}...)
}
这篇关于在Go中连接两个切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文