Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
package config

// Valid package variable declaration with explicit type
var maxConnections int = 100

// Valid package variable with type inference
var defaultTimeout = 30

// INVALID: Short declaration cannot be used at the package level
// retryLimit := 5 

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.
package server

// Exported: Accessible via server.Port from other packages
var Port string = ":8080"

// Unexported: Accessible only within the 'server' package
var connectionCount int = 0

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.
package database

var (
    // Exported variables
    Host string = "localhost"
    User string = "admin"
    
    // Unexported variables
    poolSize int  = 20
    isActive bool = false
)

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).
package metrics

// Implicitly initialized to 0
var requestCounter int

// Implicitly initialized to nil
var activeConnections []string
Master Go with Deep Grasping Methodology!Learn More