Search code examples
gogo-map

Slice out of bounds using [][]int but works with map[int][]int


Why does this code work

graph := make(map[int][]int, 0)

graph[0] = append(graph[0], 1)

But if you replace first line with graph := make([][]int, 0) I get panic: runtime error: index out of range? It's very weird.


Solution

  • When you do make in graph := make(map[int][]int, 0), you are allocating memory to your map, not to array. So you might do this only graph := make(map[int][]int).

    Decomping you code:

    type a []int
    type m map[int]a
    
    func main() {
        fmt.Println("Hello, playground")
    
        //decomping graph := make(map[int][]int, 0)
        graph := make(m)
    
        //map is empty
        fmt.Println(len(graph))
    
        //decomping graph[0] := append(graph[0], 1)
        itm_a := 1
        arr_a := []int{}
    
        //appeding item to "a" type
        arr_a = append(arr_a, itm_a)
    
        //appending array of a to graph
        graph[0] = arr_a
    
        //print graph
        fmt.Println(graph)
    }
    

    See in playground.

    The error that you are getting is caused for conceptual error. When you does graph := make([][]int, 0), you are allocation memory to a slice of slice, not an array. See in https://blog.golang.org/go-slices-usage-and-internals.

    So you can does this (decomping solution):

    type a []int
    type m []a
    
    func main() {
        fmt.Println("Hello, playground")
    
        //decomping graph := make([][]int, 0)
        //see that you must be set the length
        graph := make(m, 0)
    
        //map is empty
        fmt.Println(len(graph))
    
        //this is incorrect: graph[0] := append(graph[0], 1)
        //this is correct:   graph[0] := append(graph[0], []int{1})
        //see:
        itm_a := 1
        arr_a := []int{}
    
        //appeding item to "a" type
        arr_a = append(arr_a, itm_a)
    
        //appending slice of a to graph (slice)
        graph = append(graph, arr_a)
    
        //print graph
        fmt.Println(graph)
    }
    

    See in playground