英文:
What is the fastest way to append one array to another in Go?
问题
假设我在Go语言中有数组A
和B
。将B
的所有值追加到A
的最快方法是什么?
英文:
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
得分: 18
在Go语言中,数组(Arrays)是次要的,切片(Slices)才是更常用的方式。Go语言提供了内置的append()
函数来追加切片:
a := []int{1, 2, 3}
b := []int{4, 5}
a = append(a, b...)
fmt.Println(a)
输出结果为:
[1 2 3 4 5]
你可以在Go Playground上尝试运行代码。
注意:
在Go语言中,数组的大小是固定的:一旦创建了数组,就无法增加其大小,因此无法向其追加元素。如果需要追加元素,你需要分配一个新的更大的数组,足够容纳两个数组中的所有元素。而切片则更加灵活。
在Go语言中,数组非常“不灵活”,甚至数组的大小也是其类型的一部分。例如,数组类型[2]int
与[3]int
是不同的类型,因此即使你创建了一个用于添加/追加[2]int
类型数组的辅助函数,你也无法将其用于追加[3]int
类型的数组!
阅读以下文章以了解更多关于数组和切片的知识:
英文:
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论