Home
Go
Global Variable Example
This page was last reviewed on Feb 21, 2024.
Dot Net Perls
Global variable. Suppose you have a web server or other threaded Go program that must read in command-line arguments. We can use global variables (with var) to store this data.
For things like command-line arguments, no mutations are needed after initial assignment. This makes the global variable safe to use across threads.
Example. This Go program reads in a command-line argument "x" with the flag.Int method and flag.Parse. The value passed into the program is stored in the global variable GlobalX.
Step 1 We set up (with flag.Int) and parse (with flag.Parse) the command-line argument with the flag package.
flag
Step 2 We store the value from the command-line argument in the global int variable GlobalX.
Step 3 This part of the example creates multiple threads (with the go-keyword) and calls a method "example" on them.
Step 4 We access the global variable and print out its value. Any method (even on a thread) can access the global variable.
Step 5 We sleep to allow all the go-routines to terminate. A better solution is WaitGroup, but this would make the example more complicated.
package main import ( "fmt" "flag" "time" ) var GlobalX int func example() { // Step 4: use the global variable in a method called on different threads. fmt.Println(GlobalX) } func main() { // Step 1: read in a command-line argument. x := flag.Int("x", 0, "") flag.Parse() // Step 2: store the argument in a global variable. GlobalX = *x // Step 3: call a method on multiple threads with the go-keyword. for i := 0; i < 5; i += 1 { go example() } // Step 5: wait a while for the threads to run. time.Sleep(100 * time.Millisecond) }
go run program.go --x 10
10 10 10 10 10
Summary. It is possible to a global variable across methods and even threads in the Go programming language. This can be useful for values that are initialized once and then read repeatedly.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 21, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.