Initialize a 2d dynamic array in Go

arnab picture arnab · May 26, 2014 · Viewed 10.6k times · Source

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).

Answer

James Henstridge picture James Henstridge · May 26, 2014

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"