Golang Global Variables

Golang Global Variables

We can define a variable outside the function, these are called Golang Global Variables. These variables can be accessed by any function in the package.

Golang Global Variables Example

Let’s have a look at a simple example of global variable in Golang.

package main

import "fmt"

var x = 10

func main() {
	fmt.Println(x)
	foo()
}

func foo() {
	fmt.Println(x * 2)
}

When you execute the above code, the output will be:

10
20

Global Variables are Editable

Global variables in Go are editable. Any code in any of the functions can edit the global variable.

package main

import "fmt"

var x = 10

func main() {
	fmt.Println(x)
	x = 20 // editing global variable
	foo()
}

func foo() {
	fmt.Println(x)
}

Output:

10
20

Global Variable and Local Variable Preference

Golang allows variables of the same name if the scopes are different. So, we can define a variable named ‘x’ inside the function too. In this case, which variable will get the preference?

The local variable will get more preference than the global variable.

package main

import "fmt"

var x = 10

func main() {
	x = 50 // local variable of same name
	fmt.Println(x) // prints 50
}

Global Variables – Use or Not

  • The biggest problem with global variables is that they are editable. There is a high chance that some unintended code will edit the global variable and create unwanted bugs in the program.
  • The only time I think global variables make sense are when it’s a constant and it will be used by many functions. For example, PI or natural log base.

Further Readings: Variables in Golang