What is the fastest way to append one array to another in Go?

白昼怎懂夜的黑 提交于 2020-01-15 18:51:31

问题


Suppose that I have arrays A and B in Go. What is the fastest way to append all the values of B to A?


回答1:


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:

Go Slices: usage and internals

Arrays, slices (and strings): The mechanics of 'append'



来源:https://stackoverflow.com/questions/28957190/what-is-the-fastest-way-to-append-one-array-to-another-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!