Search code examples
dictionaryglobal-variablesgo

Create global map variables


I need a little help regarding creating a global map variable in Go. What I have done is as follows:

package ...
import(
...
)
...
type ir_table struct{
    symbol      string
    value       string
}
var ir_MAP map[int]ir_table

Since I am not initializing the map, I am getting a nil pointer dereference error. What must I do to use this variable globally? Or, if this is not a correct way to do this, please guide me.


Solution

  • You need to initialize it with an empty map:

    var ir_MAP = map[int]ir_table{}
    

    or, as "the system" suggested:

    var ir_MAP = make(map[int]ir_table)
    

    The problem is that the zero value of a map is nil, and you can't add items to a nil map.