Varun Patro
Varun Patro

Reputation: 2179

How to initialize a slice of maps correctly

So I want to be able to create a slice of maps such that when I access any element of the slice, I get a not-nil map.

Here is my code so far. But I get the error of panic: assignment to entry in nil map

package main

import (
    "fmt"
)

func main() {
    all := make([]map[string]string, 3)
    first := all[0]
    first["hello"] = "world"
    fmt.Println(all)
}

Upvotes: 0

Views: 57

Answers (1)

DAXaholic
DAXaholic

Reputation: 35338

I think the author wants to pre-init the slice with default instances like so

func main() {
    all := make([]map[string]string, 3)
    for idx, _ := range all {
      all[idx] = map[string]string{}
    }
    first := all[0]
    first["hello"] = "world"
    fmt.Println(all)
}

Upvotes: 3

Related Questions