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.
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
.
flag.Int
) and parse (with flag.Parse
) the command-line argument with the flag package.int
variable GlobalX
.go
-keyword) and calls a method "example" on them.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 1010 10 10 10 10
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.