go.mod and go.sum Explained
In this page:
What go.mod Contains
go.mod records the module's own import path, the minimum Go version it targets, and a require block listing every direct (and sometimes indirect) dependency with an exact version.
Example: What go.mod Contains
module github.com/example/myapp
go 1.22
require github.com/some/dependency v1.4.0
⚠️ Run this command in your terminal.
What go.sum Contains
go.sum stores cryptographic hashes for every dependency's exact content, so that anyone building the project gets bit-for-bit the same code -- protecting against a compromised or accidentally altered package.
Example: What go.sum Contains
github.com/some/dependency v1.4.0 h1:abcdef1234567890...
github.com/some/dependency v1.4.0/go.mod h1:1234567890abcdef...
⚠️ Run this command in your terminal.
Keeping Dependencies Tidy
'go mod tidy' scans your source code's actual imports and updates go.mod/go.sum to match exactly -- adding anything missing and removing dependencies that are no longer actually imported anywhere.
Note: Run 'go mod tidy' before committing whenever you add or remove imports.
Example: Keeping Dependencies Tidy
go mod tidy
⚠️ Run this command in your terminal.
Why Commit Both Files
Committing go.mod and go.sum together to version control guarantees every developer, and every CI build, resolves dependencies to the exact same versions with verified content -- this is what makes Go builds reproducible.
Example: Why Commit Both Files
package main
import "fmt"
func main() {
fmt.Println("go.mod + go.sum, committed together, make builds reproducible")
}
Login to try C/C++/Java/PHP code in the editor
- Editing go.sum by hand -- it's machine-generated and should only be updated by running go commands.
- Deleting go.sum thinking it's unnecessary, when it's what protects the build from tampered or corrupted dependencies.
- Committing go.mod but forgetting to commit go.sum, breaking reproducible builds for other developers.
- go.mod declares the module's identity, Go version, and its required dependencies with versions.
- go.sum records cryptographic checksums for every dependency, verifying their integrity.
- Both files should always be committed to version control together.
- 'go mod tidy' keeps go.mod and go.sum accurate, adding missing and removing unused requirements.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: