Search code examples
govariablesmemory-managementhashmapdynamic-memory-allocation

In maps even though I can print the value, why I cannot change it?


var sudoku = map[int][9]int{   // map of 9 x 9 
    0: {3, 0, 6, 5, 0, 8, 4, 0, 0},
    1: {5, 2, 0, 0, 0, 0, 0, 0, 0},
    2: {0, 8, 7, 0, 0, 0, 0, 3, 1},
    3: {0, 0, 3, 0, 1, 0, 0, 8, 0},
    4: {9, 0, 0, 8, 6, 3, 0, 0, 5},
    5: {0, 5, 0, 0, 9, 0, 6, 0, 0},
    6: {1, 3, 0, 0, 0, 0, 2, 5, 0},
    7: {0, 0, 0, 0, 0, 0, 0, 7, 4},
    8: {0, 0, 5, 2, 0, 6, 3, 0, 0},
}
fmt.Println("Old value:", sudoku[1][0])
sudoku[1][0] = append(sudoku[1][0],10) 
fmt.Println("New value:", sudoku[1][0])

Value is not changed, error message- cannot assign to sudoku[1][0]


Solution

  • sudoku[1][0] is an int, you can't append to an int, only to slices. Also [9]int is an array, not a slice.

    You most likely want to change an element, not append to it, so use a simple assignment:

    sudoku[1][0] = 10
    

    This will output (try it on the Go Playground):

    Old value: 5
    New value: 10
    

    Strongly recommended to take the Go Tour if you're not clear with the basics.