Search code examples
arraysgoslicesudoku

Can't make a slice of a column of a 2d array "cannot use Sudoku[0:9][0] (type [9]int) as type []int in assignment"


I'm making a simple game of sudoku using slices of a 9x9 2d array. I'm still starting out with Golang and have some C++ experience. I keep getting the error message "cannot use Sudoku[0:9][0] (type [9]int) as type []int in assignment".

var row1 []int = Sudoku[0][0:9] This line correctly took the values of the first row of the 2d array and placed them into the row1 slice, but using var col1 []int = Sudoku[0:9][0] results in the error message above. What can I do? Thanks in advance!

For example,

package main

import "fmt"

func main() {
    var Sudoku [9][9]int
    fmt.Println(Sudoku)
    var row1 []int = Sudoku[0][0:9]
    fmt.Println(row1)
    var col1 []int = Sudoku[0:9][0]
    fmt.Println(col1)
}

Playground: https://play.golang.org/p/Jk6sqqXR5VE

10:6: cannot use Sudoku[0:9][0] (type [9]int) as type []int in assignment

Solution

  • var col1 []int = Sudoku[0:9][0] gets you an array, not a slice. You could either declare as var col1 [9]int = Sudoku[0:9][0] (or better: col1 := Sudoku[0:9][0]), or if you really want a slice: var col1Slice []int = col1[:] after getting col1.

    In general, things would be much easier if your sudoku structure were a 2D slice instead of 2D array, then you'd be dealing with only slices.

    Working example of all of these: https://play.golang.org/p/LE8qwFSy1m_e