Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go : assignment to entry in nil map

When trying to set value to the map(countedData) in the below code, I am getting an error that says, assignment to entry in nil map.

func receiveWork(out <-chan Work) map[string][]ChartElement {

    var countedData map[string][]ChartElement

    for el := range out {
        countedData[el.Name] = el.Data
    }
    fmt.Println("This is never executed !!!")

    return countedData
}

Println does not execute (as the error occurs on a lien before that).

There are some goroutines , that are sending data to channel, and receiveWork method should be making a map like this:

map =>
    "typeOne" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ],
    "typeTwo" => 
       [
         ChartElement,
         ChartElement,
         ChartElement,
       ]

Please help me fix the error.

like image 556
Altenrion Avatar asked Feb 13 '16 11:02

Altenrion


2 Answers

The Go Programming Language Specification

Map types

A new, empty map value is made using the built-in function make, which takes the map type and an optional capacity hint as arguments:

make(map[string]int)
make(map[string]int, 100)

The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps. A nil map is equivalent to an empty map except that no elements may be added.

You write:

var countedData map[string][]ChartElement

Instead, to initialize the map, write,

countedData := make(map[string][]ChartElement)
like image 132
peterSO Avatar answered Oct 10 '22 12:10

peterSO


Another option is to use a composite literal:

countedData := map[string][]ChartElement{}

https://golang.org/ref/spec#Composite_literals

like image 41
Zombo Avatar answered Oct 10 '22 10:10

Zombo