go.mod and go.sum Explained
In this page:
module module/path
go 1.21
require example.com/pkg v1.2.3
// go.sum: module version hash
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 in your own terminal or Node.js environment.
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 in your own terminal or Node.js environment.
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.
Example: Keeping Dependencies Tidy
go mod tidy
⚠️ Run this in your own terminal or Node.js environment.
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
// 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("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: