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:
import (
"fmt"
)
var global int
funcmain() {
multiply()
}
funcmultiply() {
global = 10
fmt.Println(global
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:
0
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.
import (
"fmt"
)
var global = 10
funcmain() {
global = global * 2
fmt.Println(global)
}
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?
For example:
import (
"fmt"
)
var age = 60
funcmain() {
age := 20
fmt.Println(age)
}
Will the code above print 60 or 20?
The output is as shown:
20
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.
Conclusion
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.