Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allocate a non-constant sized array in Go

Tags:

arrays

go

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 How to implement resizable arrays in Go for an answer, but that is a different question.)

like image 511
Steve Powell Avatar asked Apr 25 '14 10:04

Steve Powell


People also ask

Does Go have dynamic arrays?

Go arrays are fixed in size, but thanks to the builtin append method, we get dynamic behavior. The fact that append returns an object, really highlights the fact that a new array will be created if necessary.

Can you resize an array in Golang?

But arrays in Golang cannot be resized, hence we have slices, whose size can be dynamically changed. Slices have length and capacity.

How do I create an array of variable size in Golang?

You can build an array using the make builtin function. I use one of the two forms: a := make([]int,10) a := make([]int,0,10)


1 Answers

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

like image 158
Steve Powell Avatar answered Oct 18 '22 13:10

Steve Powell