Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 545
progfan Avatar asked Mar 02 '13 18:03

progfan


People also ask

Can you create your own global variables?

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode. window is available only in browsers.

How do you create a global variable?

The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.

What is globalMap put in Talend?

Talend provides the globalMap Object where both Talend and you can store and retrieve data. This is a great place to create your global variables as well as retrieving important information about your executing Job. globalMap is my preference for storing global data that is specific to a particular Job.


2 Answers

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.

like image 121
andybalholm Avatar answered Oct 02 '22 09:10

andybalholm


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, } 
like image 44
Jagger Yu Avatar answered Oct 02 '22 09:10

Jagger Yu