HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Dynamically initialize array size in go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayinitializesizedynamically

Problem

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 {

Code Snippets

//var array = new([elems]int) - no, arrays are not dynamic
var slice = make([]int,elems) // or slice := make([]int, elems)
// for i := 0; i < elems; i++ { - correct but less idiomatic
for i, v := range slice {

Context

Stack Overflow Q#8539551, score: 167

Revisions (0)

No revisions yet.