Fundamentals 11 min read

Understanding Go Package Import Paths, Compilation Process, and Naming Conventions

This article explains how Go organizes source files into packages, the difference between import paths and package names, how the compiler chooses between source code and compiled .a files, the role of import aliases, and why a directory can contain only one package.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Understanding Go Package Import Paths, Compilation Process, and Naming Conventions

Go uses the package keyword to group source files, and the import statement to reference other packages. The import path is a file‑system path, not the package name; the last element of the path is the directory that contains the package source.

Example of a simple package definition:

package xxx

Importing a standard library package:

import "fmt"

When a third‑party package is imported, the compiler first compiles the source into a temporary .a file and then links it. If both the source directory and a pre‑built .a exist, the compiler prefers the freshly compiled .a from the source.

Experiments show that removing the source directory while keeping the .a file causes a build failure, confirming that the compiler still searches for the source path.

For the Go standard library (e.g., fmt ), the compiler also requires the source directory; renaming $GOROOT/src/fmt makes the package unavailable, even though the compiled fmt.a exists.

The import path’s final element is a directory, not the package name. A directory may contain only one package; attempting to place files with different package declarations (e.g., foo and bar ) in the same directory results in a build error.

Import aliases allow a different local name for a package:

import m "lib/math"

After this, the package can be accessed as m.Sin . The alias m refers to the package found in the lib/math directory, regardless of the package’s internal name.

Overall, the article demonstrates that Go’s import mechanism treats the path as a directory, the package name is defined inside the source files, and a directory can host only one package, while import aliases provide flexible naming in code.

CompilationGo@Importstandard-librarypackagesalias
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.