Understanding Go Packages: Basics and Management with Go Modules
This article explains Go's package system, covering package declaration, classification, import mechanics, identifier visibility, the init function, and how to manage dependencies using Go Modules from Go 1.11 onward.
Go packages are the fundamental unit for organizing and managing code, improving reuse, maintainability, and readability.
Each source file belongs to a package declared at the top with the package keyword, e.g., package main. Packages consist of one or more .go files in the same directory, and the package name should be descriptive and match the folder name, using lowercase letters.
Packages are classified as:
Main package : named main, compiled into an executable; a program can have only one.
Non‑main package : library code that other packages can import.
Custom package : created by the developer.
Third‑party package : obtained from external sources such as GitHub.
To use code from another package, the import keyword is used, for example import "fmt". An alias can be provided to avoid name clashes, e.g., import f "fmt". When a package is imported, any init function it defines is executed automatically; init has no parameters or return values and is intended for package‑level initialization.
Visibility of identifiers is controlled by the first letter's case: identifiers starting with an uppercase letter are exported and accessible to other packages, while those starting with a lowercase letter are private to the package. Example:
package package_demovar
PublicVar = "I am public" // exported variable
var privateVar = "I am private" // unexported variable
func PublicFunc() { fmt.Println("Public function") } // exported function
func privateFunc() { fmt.Println("Private function") } // unexported functionSince Go 1.11, Go Modules replace the old GOPATH workflow. Running go mod init project creates a go.mod file, marking the start of a module. Subsequent commands such as go get, go mod download, and go mod vendor are used to add, download, and vendor dependencies, respectively.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
