Dynamically initialize array size in go

Issue

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?

Solution

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 {

Answered By – Paolo Falabella

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.