How Gloabal variables work in golang

(akhil) #1

I have created a global variable in a package and stored value in that.

Now I have created another application and stored the vale and before printing the value I have called the sleep function for 10 sec and then printed it.

In the meanwhile, I have called the same application again in the other terminal removing the sleep and changing the value stored in the global.

But then I found that both print the values what I have send (differently) But as of my knowledge, global values should be affected when they are changed.

I don’t know whether my understanding is wrong or go works like that. Can anyone help me.


(Boban Acimovic) #2

It is bad idea to use global variables anyways, why do you need them? Being global doesn’t mean you can access it from another application, they do not share memory. I hope I understood you correctly.

(George Calianu) #3

Are some specific cases where the globals are useful. I guess some common cases are database operations or when you work with templates. Also, i saw some uses of global protected maps, instead channels, in concurency. I don’t figured out if is a good practice or not, though…

(akhil) #4

As geosoft1 said I need to store the statement handle created by a driver in the global variable and use it in the other function.

(akhil) #5

Since both applications are running on different processors the global variables are different I get it. Suppose if any one wants to access the value stored by the other application, can he access it?

(Boban Acimovic) #6

You can also pass this variable to places where you need it, it is not necessary to make it global.

(Ali Koyuncu) #7

Global variables doesn’t mean global on entire machine. They are global in their process-address space.