Follow us along as we explore the concept of global variables in the go programming language.
Golang Global Variable
As mentioned, we define global variables outside any function. Typically, global variables are defined on top of the program before the main function. After declaration, a global variable can be accessed and changed at any part of the program.
An example of a global variable is as shown in the program below:
var global int
global = 10
In the example above, we declare a global variable called “global”. We then set the value for the variable inside the multiply function.
NOTE: If you access the value of the global variable inside the main function, its value is 0 as shown:
You can also declare an initialize a global variable as shown:
Any part of the program can change the value of a global variable. For example, the code below changes the value of the global variable to 20.
var global = 10
global = global * 2
In the example above, we reassign the value of the global variable inside the main function. Keep in mind that all the codes after the modification will reflect the recent value of the global variable.
Global Vs Local Variables
The next question you may ask is? What happens if there is a local variable with the same name as a global variable?
var age = 60
age := 20
Will the code above print 60 or 20?
The output is as shown:
This is because the compiler gives preference to local variables than global. Hence, if a local and global variable share a name, the compiler will always choose the local variable.
In this guide, we discussed how to create and use global variables. Since any part of the program can change the value of a global variable, it is recommended to use global variables as constants.