Skip to main content
A package variable in Go is a variable declared at the package level, outside of any function body. Its lexical scope encompasses all source files belonging to the same package, meaning it can be accessed and mutated by any function within that package.

Declaration Syntax

Package variables must be declared using the var keyword. The short variable declaration operator (:=) is strictly prohibited at the package level and will result in a compilation error.

Visibility and Export Rules

Go uses identifier casing to determine the visibility of package variables across package boundaries.
  • Exported: If the variable name begins with an uppercase letter, it is exported and can be accessed by external packages that import the declaring package.
  • Unexported: If the variable name begins with a lowercase letter or an underscore, it is unexported and strictly confined to the package in which it is declared.

Grouping

Multiple package variables can be grouped within a single var block. This is the idiomatic approach for declaring multiple package-level variables, as it reduces keyword repetition.

Initialization and Zero Values

Package variables are initialized exactly once per package, during the package initialization phase. This occurs prior to the execution of any init() functions and before the main() function begins. If a package variable is declared without an explicit initial value, the Go compiler automatically assigns it the zero value for its respective type (e.g., 0 for numeric types, "" for strings, false for booleans, and nil for pointers, slices, maps, and channels).
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More