Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...) 
like image 825
Kevin Burke Avatar asked Apr 27 '13 04:04

Kevin Burke


People also ask

How do you concatenate slices in Golang?

When it comes to appending a slice to another slice, we need to use the variadic function signature dots. In variadic functions in Golang, we can pass a variable number of arguments to the function and all the numbers can be accessed with the help of the argument name.

How do you concatenate slices?

Type) []Type The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.

How do I concatenate strings in Golang?

In Go strings, the process of adding two or more strings into a new single string is known as concatenation. The simplest way of concatenating two or more strings in the Go language is by using + operator . It is also known as a concatenation operator. str1 = "Welcome!"

How do I append an array in Golang?

There is no way in Golang to directly append an array to an array. Instead, we can use slices to make it happen. The following characteristics are important to note: Arrays are of a fixed size.


1 Answers

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}...) } 
like image 144
4 revs, 3 users 84%user1106925 Avatar answered Sep 20 '22 03:09

4 revs, 3 users 84%user1106925