在Go中将一个数组追加到另一个数组的最快方法是什么? [英] What is the fastest way to append one array to another in Go?

查看:141
本文介绍了在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?

推荐答案

Gos中的数组是次要的, 切片 是解决之道。 Go提供了内置的 append() 函数来附加片:

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)

输出:

[1 2 3 4 5]

去游乐场上尝试。

注意:

Go中的数组是固定大小的:一旦创建数组,则无法增加其大小,因此无法向其添加元素。如果需要,您将需要分配一个更大的新数组。大到足以容纳2个数组中的所有元素。切片要灵活得多。

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.

Go中的数组是如此不灵活,以至于数组的大小也是其类型的一部分,例如,数组类型 [2] int 与类型 [3] int 不同,因此即使您要创建一个辅助函数来添加/添加数组类型为 [2] int 的数组不能附加类型为 [3] int 的数组!

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中将一个数组追加到另一个数组的最快方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆