golang

Golang Global Variables

A global variable refers to a variable that is defined outside a function. Global variables can be accessed throughout the program or within any function in the defined package.

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:

package main
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:

fmt.Println(global)

0

You can also declare an initialize a global variable as shown:

var global = 10

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.

package main
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:

package main
import (
    "fmt"
)

var age = 60
funcmain() {
    age := 20
    fmt.Println(age)
}

Will the code above print 60 or 20?

The output is as shown:

$ go run global.go

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list