如何在Go语言中分配非常量大小的数组

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

How to allocate a non-constant sized array in Go

问题

在Go语言中,如果你想在运行时分配一个数组,可以使用切片(slice)来实现。切片是一个动态大小的数组,可以根据需要进行扩展或缩小。

下面是使用切片来分配数组的示例代码:

n := 1
a := make([]int, n)

这样就可以在运行时根据需要分配一个大小为n的数组。请注意,这里使用的是切片(slice)而不是数组(array)。

希望对你有帮助!如果你还有其他问题,请随时提问。

英文:

How do you allocate an array in Go with a run-time size?

The following code is illegal:

 n := 1
 var a [n]int

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.

(By the way, I first looked in the question https://stackoverflow.com/q/3387273/57171 for an answer, but that is a different question.)

答案1

得分: 22

答案是你不直接分配一个数组,而是在创建切片时让Go为你分配一个。

内置函数make([]T, length, capacity)创建一个切片和其背后的数组,并且对lengthcapacity的值没有(愚蠢的)编译时常量限制。正如在Go语言规范中所说:

> 使用make创建的切片总是会分配一个新的隐藏数组,返回的切片值指向该数组。

因此,我们可以这样写:

 n := 12
 s := make([]int, n, 2*n)

这样就会分配一个大小为2*n的数组,并且s是一个初始化为前半部分的切片。

我不确定为什么Go不直接分配[n]int数组,因为你可以间接地做到,但答案很明确:“在Go中,大多数情况下使用切片而不是数组”。

英文:

The answer is you don't allocate an array directly, you get Go to allocate one for you when creating a slice.

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)

and have an array allocated size 2*n, with s a slice initialised to be the first half of it.

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)."

huangapple
  • 本文由 发表于 2014年4月25日 18:45:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/23290858.html
匿名

发表评论

匿名网友

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

确定