Packages & Modules in Go
As Go programs grow, organizing code becomes critical. Go solves this using packages and modules. These concepts help you write clean, reusable, and maintainable applications.
Almost every real-world Go project relies on packages and modules.
What Is a Package?
A package is a collection of Go files stored in the same directory. All files in a package belong to the same namespace.
Every Go file starts with a package declaration.
package main
This tells Go which package the file belongs to.
The main Package
The main package is special.
A Go program must have a main package and a main() function.
package main
func main() {
println("Hello Go")
}
Only the main package produces an executable program.
Creating a Custom Package
Let’s create a real example using business-style data.
Directory structure:
project/
├─ main.go
└─ mathutils/
└─ calc.go
package mathutils
func Add(a int, b int) int {
return a + b
}
This file defines a reusable package called mathutils.
Importing a Package
Now import and use it in main.go.
package main
import (
"fmt"
"project/mathutils"
)
func main() {
result := mathutils.Add(10, 20)
fmt.Println(result)
}
Go imports packages using their module path.
Exported vs Unexported Names
In Go, visibility is controlled by capitalization.
- Names starting with uppercase are exported
- Names starting with lowercase are private
func add(a int, b int) int { // private
return a + b
}
func Add(a int, b int) int { // exported
return a + b
}
Only exported names can be accessed from other packages.
What Is a Module?
A module is a collection of related packages. Modules also manage dependency versions.
Go modules are defined using a go.mod file.
Initializing a Go Module
Create a module in your project root:
go mod init github.com/yourname/project
This creates a go.mod file.
Understanding go.mod
Example go.mod file:
module github.com/yourname/project
go 1.22
This file defines:
- Module name
- Go version
- External dependencies
Adding External Dependencies
Go automatically downloads dependencies when you import them.
import "github.com/google/uuid"
Run:
go mod tidy
This updates go.mod and creates go.sum.
Package Naming Rules
- Package names should be short
- Use lowercase letters
- Avoid underscores and plural names
- Name packages by purpose, not type
Standard Library Packages
Go comes with a rich standard library.
fmt– formatting and printingnet/http– web serversos– operating system functionstime– date and time
Real-World Usage
In production Go systems:
- Each feature is a package
- Modules define service boundaries
- Dependencies are version-locked
- CI/CD relies on
go.mod
Best Practices
- One package per directory
- Keep packages focused
- Avoid circular imports
- Use modules for version control
What’s Next?
In the next lesson, you will learn about Error Handling in Go, including best practices for building robust and fault-tolerant applications.