Skip to main content
A Go package is a fundamental unit of code organization, compilation, and encapsulation, consisting of one or more .go source files residing in the same directory. All files within a package share the same namespace and are compiled together as a single entity, allowing internal declarations to be mutually accessible regardless of the specific file in which they are defined.

Package Declaration

Every Go source file must declare its package membership as the first non-comment line of code.
By convention, the package name is a short, lowercase word that matches the base name of the directory containing the files. All .go files within a single directory must declare the exact same package name, with the strict exception of test files (_test.go), which may optionally use a _test suffix (e.g., mathutils_test).

Visibility and Export Rules

Go does not use access modifier keywords (like public or private). Instead, it relies on lexical casing to determine the visibility of identifiers (variables, constants, functions, types, and struct fields) across package boundaries.
  • Exported (Public): Identifiers beginning with an uppercase letter are accessible to external packages that import them.
  • Unexported (Private): Identifiers beginning with a lowercase letter are strictly scoped to the declaring package.

The main Package

The main package is a special designation that instructs the Go compiler to build an executable binary rather than a shared library archive. A main package must contain a main() function, which the Go runtime invokes as the entry point of the application.

Importing Packages

To consume exported identifiers from another package, a file must declare an import block. The string provided is the import path, which is a globally unique identifier derived from the project’s go.mod file and the directory structure.
Import Modifiers: Go provides specific syntax to modify how a package is imported into the current file’s namespace:

Package Initialization

A package can define one or more init() functions to perform setup tasks before the program executes. The Go runtime guarantees that init() functions are called sequentially after all package-level variable declarations are evaluated, and strictly before the main() function begins.
If a package imports other packages, the imported packages are initialized first. A single package can contain multiple init() functions across its files, which are executed in lexical file name order.
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More