Create global map variables

You almost have it right. You just haven't initialized your map yet.

Here's working code in The Playground.

package main

import "fmt"

type ir_table struct{
    symbol      string
    value       string
}
// define global map; initialize as empty with the trailing {}
var ir_MAP = map[int]ir_table{}

func main() {
    ir_MAP[1] = ir_table{symbol:"x", value:"y"}
    TestGlobal()
}

func TestGlobal() {
    fmt.Printf("1 -> %v\n", ir_MAP[1])
}

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.


You can directly initialize a map like this:

var Romans = map[byte]int{
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000,
}

old topic, but the most elegant solution hasn't been mentioned. This is quite useful in modules where it's not possible to assign values in the main function. init is executed only once so it saves a few CPU cycles every time the map would have to be initialized otherwise.

https://play.golang.org/p/XgC-SrV3Wig

package main

import (
    "fmt"
)

var (
    globalMap = make(map[string]string)
)

func init() {
    globalMap["foo"] = "bar"
    globalMap["good"] = "stuff"
}

func main() {
    fmt.Printf("globalMap:%#+v", globalMap)
}