I am trying to create a 2d array in Go:
board := make([][]string, m)
for i := range board {
board[i] = make([]string, n)
}
However, given the verbosity of that, I am wondering if there is a better or more succinct way to handle this problem (either to generate dynamic arrays, or a different/idiomatic data-structure to handle such board-game like data)?
Background:
To create a 2D array we must specify each dimension. We can then assign individual elements within the array. Here we create a 2 by 2 array of strings. Tip Arrays in Go have fixed sizes.
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)
In some dynamically typed programming languages, there's the functionality of a dynamic array by default. But statically typed programming language like Go does not have the functionality of a dynamic array.
What you are building in your sample code is not a 2D array, but rather a slice of slices: each of the sub-slices could be of a different length with this type, which is why you have separate allocations for each.
If you want to represent the board with a single allocation though, one option would be to allocate a single slice, and then use simple arithmetic to determine where elements are. For example:
board := make([]string, m*n)
board[i*m + j] = "abc" // like board[i][j] = "abc"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With