Senior
What can a global variable be used for in Go?
sobes.tech AI
Answer from AI
Global variables in Go are used to store state or data that should be accessible across many functions or packages without needing to pass them explicitly through parameters. This is convenient for configuration settings, caching, counters, or shared resources.
However, it is important to remember that global variables can create challenges with concurrent access in multi-threaded programs, so their use often involves synchronization (e.g., mutex) to prevent data races.
Example of using a global variable with a mutex:
package main
import (
"fmt"
"sync"
)
var (
counter int
mu sync.Mutex
)
func increment() {
mu.Lock()
defer mu.Unlock()
counter++
}
func main() {
increment()
fmt.Println(counter) // 1
}
Thus, global variables are useful for storing shared data but require careful management in a concurrent environment.