Go Modules and go.mod
In this page:
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?
package main
import "fmt"
func main() {
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.
Note: Use a real or placeholder repository path, e.g. 'github.com/yourname/project', even for local-only projects.
Example: Creating go.mod with go mod init
go mod init github.com/example/myapp
⚠️ Run this command in your terminal.
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 command in your terminal.
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.
Note: 'go get' updates both go.mod and go.sum; never edit go.sum manually.
Example: Adding Dependencies
go get github.com/some/[email protected]
⚠️ Run this command in your terminal.
- 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: