用户输入的数组大小[重复]

This question already has an answer here:

I have this bit of code:

fmt.Scanf("%dx%d", &sizex, &sizey)  
var grid [sizex][sizey]int

I'm currently getting the "non-constant array bound sizex" error. How can I create array with dimensions chosen by user? Of course, I don't want to modify its size later, but I obviously can't use constants.

</div>

I think you're looking for;

grid := make([][]int, sizex)
for i := 0; i < len(grid) i++ {
     grid[i] = make([]int, sizey)
}

This is sort of like using the new keyword in C++ verse regular "on the stack" allocation. To use the declaration in your question the size args would have to be values known at compile time.

In the example above make only applies to the first dimension, giving me an array of []int arrays, however, none of those arrays have been initialized so I have to iterate over grid and call make with the sizey to get the second dimension allocated.