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...)
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.
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.
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!"
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.
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}...) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With