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

huangapple go评论88阅读模式
英文:

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

问题

假设我在Go语言中有数组AB。将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:

Go Slices: usage and internals

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

huangapple
  • 本文由 发表于 2015年3月10日 14:10:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/28957190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定