如何在 Go 中分配一个非常量大小的数组 [英] How to allocate a non-constant sized array in Go

查看:26
本文介绍了如何在 Go 中分配一个非常量大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Go 中分配具有运行时大小的数组?

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

以下代码是非法的:

 n := 1
 var a [n]int

您收到消息 prog.go:12: invalid array bound n(或类似的),而这很好用:

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.

(顺便说一句,我首先查看了问题 How to implement resizable arrays in 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.

内置函数make([]T,length, capacity)创建了一个切片和它后面的数组,并且没有(傻)编译——lengthcapacity 的值的时间常数限制.正如 Go 语言规范 中所说:

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:

使用 make 创建的切片总是分配一个新的、隐藏的数组,返回的切片值引用该数组.

A slice created with make always allocates a new, hidden array to which the returned slice value refers.

所以我们可以写:

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

并且有一个分配大小的数组2*ns 一个切片被初始化为它的前半部分.

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

我不确定为什么 Go 不直接分配数组 [n]int,因为您可以间接分配数组,但答案很明确:在 Go 中,使用切片而不是数组(大多数情况下)."

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屋!

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