Go Modules and go.mod
In this page:
module module/path
go 1.21
require example.com/pkg v1.2.3
What Is a Module?
A Go module is a collection of related packages that are versioned and distributed together, identified by a module path (often a repository URL like github.com/user/project).
Modules are Go's unit of dependency management, similar to a package.json in Node.js or a Cargo.toml in Rust.
Example: What Is a Module?
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Print the values followed by a newline
fmt.Println("A module groups packages under one versioned identity")
}
Login to try C/C++/Java/PHP code in the editor
Creating go.mod with go mod init
Running 'go mod init' followed by a module path creates a go.mod file in the current directory.
This file records the module's name and the minimum Go version it requires, and it becomes the anchor that all import paths within the project are resolved against.
Example: Creating go.mod with go mod init
go mod init github.com/example/myapp
⚠️ Run this in your own terminal or Node.js environment.
Reading a go.mod File
A go.mod file lists the module directive (its name), a go directive (minimum Go version), and a require block listing each dependency module with its exact version. Go tooling reads this file automatically -- you rarely edit it by hand.
Example: Reading a go.mod File
module github.com/example/myapp
go 1.22
require (
github.com/some/dependency v1.4.0
)
⚠️ Run this in your own terminal or Node.js environment.
Adding Dependencies
When your code imports a package that isn't part of the standard library, you fetch and record it with 'go get'.
This updates go.mod with the new requirement and creates or updates go.sum, which stores cryptographic checksums to verify dependencies haven't been tampered with.
Example: Adding Dependencies
go get github.com/some/[email protected]
⚠️ Run this in your own terminal or Node.js environment.
- Editing go.mod by hand to add a dependency instead of using 'go get', which leaves go.sum out of sync.
- Forgetting to run 'go mod init' before writing import statements for a new project, so there is no module to resolve packages against.
- Choosing a module path that doesn't match where the code is actually hosted, causing problems if the module is ever published.
- 'go mod init <module-path>' creates a go.mod file, turning a directory into a Go module.
- go.mod records the module's name, the Go version, and its dependencies with exact versions.
- Modules replaced the older GOPATH workspace system as the standard way to manage Go projects.
- Dependencies are added automatically by importing a package and running 'go build' or 'go get'.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: