Suppose that I have arrays A
and B
in Go. What is the fastest way to append all the values of B
to A
?
Arrays in Go are secondary, slices are the way to go. Go provides a built-in append()
function to append slices:
a := []int{1, 2, 3}
b := []int{4, 5}
a = append(a, b...)
fmt.Println(a)
Output:
[1 2 3 4 5]
Try it on the Go Playground.
Notes:
Arrays in Go are fixed sizes: once an array is created, you cannot increase its size so you can't append elements to it. If you would have to, you would need to allocate a new, bigger array; big enough to hold all the elements from the 2 arrays. Slices are much more flexible.
Arrays in Go are so "inflexible" that even the size of the array is part of its type so for example the array type [2]int
is distinct from the type [3]int
so even if you would create a helper function to add/append arrays of type [2]int
you couldn't use that to append arrays of type [3]int
!
Read these articles to learn more about arrays and slices: