如何分配在Go非恒定大小的数组 [英] How to allocate a non-constant sized array in Go
问题描述
你如何去同一个运行时的大小分配一个数组?
How do you allocate an array in Go with a run-time size?
以下code是非法的:
The following code is illegal:
n := 1
var a [n]int
您得到的消息 prog.go:12:无效的数组边界ñ
(或类似),而这工作得很好:
you get the message prog.go:12: invalid array bound n
(or similar), whereas this works fine:
const n = 1
var a [n]int
麻烦的是,我可能不知道数组的大小我想,直到运行时。
The trouble is, I might not know the size of the array I want until run-time.
(顺便说一句,我第一次看的问题如何实现在Go 可调整大小的阵列,以获得一个答案,但这是一个不同的问题。)
(By the way, I first looked in the question How to implement resizable arrays in Go for an answer, but that is a different question.)
推荐答案
答案是:你不分配一个 阵列的直接,你去分配一个您的创建时的的片的
The answer is you don't allocate an array directly, you get Go to allocate one for you when creating a slice.
内置的功能使([] T,长度,容量)
创建一个切片的它的背后的阵列,并有无(傻)关于长度
和容量
的值编译时间常数的限制。因为它说在进入语言规范:
The built-in function make([]T, length, capacity)
creates a slice and the array behind it, and there is no (silly) compile-time-constant-restriction on the values of length
and capacity
. As it says in the Go language specification:
与创建切片作
总是分配一个新的,隐藏的阵列到返回的切片值引用。
A slice created with
make
always allocates a new, hidden array to which the returned slice value refers.
因此,我们可以这样写:
So we can write:
n := 12
s := make([]int, n, 2*n)
和有一个数组分配的大小 2 * N
与取值
初始化是上半年片吧。
and have an array allocated size 2*n
, with s
a slice initialised to be the first half of it.
我不知道干吗去了不分配的数组 [N] INT
直接的,因为你可以做间接,但得到的答复很明确:的在围棋中,使用片而不是阵列(大部分时间)。的
I'm not sure why Go doesn't allocate the array [n]int
directly, given that you can do it indirectly, but the answer is clear: "In Go, use slices rather than arrays (most of the time)."
这篇关于如何分配在Go非恒定大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!