在 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?
我试过了:
append([]int{1,2}, []int{3,4})
但是得到:
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屋!
查看全文