The problem with doing two-dimensional arrays with Go is that you have to initialise each part individually, e.g., if you have a [][]bool
, you gotta allocate []([]bool)
first, and then allocate the individual []bool
afterwards; this is the same logic regardless of whether you're using make()
or append()
to perform the allocations.
In your example, the matrix[0]
doesn't exist yet after a mere var matrix [][]string
, hence you're getting the index out of range
error.
For example, the code below would create another slice based on the size of an existing slice of a different type:
func solve(board [][]rune, …) {
x := len(board)
y := len(board[0])
visited := make([][]bool, x)
for i := range visited {
visited[i] = make([]bool, y)
}
…
If you simply want to initialise the slice based on a static array you have, you can do it directly like this, without even having to use append()
or make()
:
package main
import (
"fmt"
)
func main() {
matrix := [][]string{{"cat", "cat", "cat"}, {"dog", "dog"}}
fmt.Println(matrix)
}
https://play.golang.org/p/iWgts-m7c4u