Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a 2d dynamic array in Go

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:

  • this is for a board game
  • the dimensions of the board are not known until a user starts playing (so, say, MxN).
  • I want to store an arbitrary character (or a single char string) in each cell. In my TicTacToe game that will be the 'X' or an 'O' (or any other character the user chooses).
like image 632
arnab Avatar asked May 26 '14 12:05

arnab


People also ask

How do I create a 2 dimensional array in Golang?

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.

How do I declare a dynamic array in Golang?

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)

Does Golang have dynamic arrays?

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.


1 Answers

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"
like image 149
James Henstridge Avatar answered Oct 20 '22 22:10

James Henstridge