Junior — Middle
Explain the concept of a global variable and its features in a program.
sobes.tech AI
Answer from AI
A global variable in Go is a variable declared outside of functions, usually in a package, and accessible throughout the package or even from other packages when exported (with a capital letter).
Features of global variables:
- Initialized when the program starts, before the main execution.
- Have package scope if the name starts with a lowercase letter, or are exported if with an uppercase.
- Used to store state accessible from different functions.
- Can cause issues with concurrent access in multithreaded programs, often requiring synchronization (e.g., using mutex).
Example of a global variable:
package main
import "fmt"
var counter int = 0 // global variable
func increment() {
counter++
}
func main() {
increment()
fmt.Println(counter) // Will print 1
}
Use of global variables should be minimized to avoid complexities in code maintenance and testing.