Fundamentals 4 min read

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.

Subtle Storm
Subtle Storm
Subtle Storm
Understanding Go Packages: Basics and Management with Go Modules

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 function

Since 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

GovisibilityGo modulesimportpackagesinit-function
Subtle Storm
Written by

Subtle Storm

The micro era's marvels are boundlessly subtle.

0 followers
Reader feedback

How this landed with the community

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.