Saturday, 16 September 2017

append - Concatenate two slices in 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...)

Answer



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}...)
}

No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...