patterngoCritical
Concatenate two slices in Go
Viewed 0 times
concatenatetwoslices
Problem
I'm trying to combine the slice
I tried:
but got:
However, the documentation seems to indicate this is possible, what am I missing?
[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 appendHowever, the documentation seems to indicate this is possible, what am I missing?
slice = append(slice, anotherSlice...)Solution
Add dots after the second slice:
This is just like any other variadic function.
// 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}...)
}Code Snippets
// 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}...)
}Context
Stack Overflow Q#16248241, score: 1564
Revisions (0)
No revisions yet.