Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically initialize array size in go

Tags:

arrays

go

I try to write a small application in go that takes 'x' numbers of integers from standard input, calculates the mean and gives it back. I have only gotten so far:

func main() { var elems, mean int sum := 0  fmt.Print("Number of elements? ")  fmt.Scan(&elems)  var array = new([elems]int)  for i := 0; i < elems; i++ {     fmt.Printf("%d . Number? ", i+1)     fmt.Scan(&array[i])     sum += array[i]; }............ 

When trying to compile this I get the following error message:

invalid array bound elems

What is wrong here?

like image 616
shutefan Avatar asked Dec 16 '11 20:12

shutefan


People also ask

Are arrays dynamic in Golang?

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.

How do I get the size of an array in Go?

To get length of an array in Go, use builtin len() function. Call len() function and pass the array as argument. The function returns an integer representing the length of the array.

How do you initialize an array in Go?

You can initialize an array with pre-defined values using an array literal. An array literal have the number of elements it will hold in square brackets, followed by the type of its elements. This is followed by a list of initial values separated by commas of each element inside the curly braces.

Are slices dynamic Golang?

But arrays in Golang cannot be resized, hence we have slices, whose size can be dynamically changed. Slices have length and capacity. Length is the number of elements present in the slice.


1 Answers

You should use a slice instead of an array:

//var array = new([elems]int) - no, arrays are not dynamic var slice = make([]int,elems) // or slice := make([]int, elems) 

See "go slices usage and internals".

Also you may want to consider using range for your loop:

// for i := 0; i < elems; i++ { - correct but less idiomatic for i, v := range slice { 
like image 88
Paolo Falabella Avatar answered Sep 21 '22 20:09

Paolo Falabella