How to Use go mod tidy: Clean and Manage Go Modules
Use
go mod tidy to clean up your Go module dependencies by adding missing ones and removing unused ones. It updates the go.mod and go.sum files to keep your project dependencies accurate and minimal.Syntax
The basic syntax of go mod tidy is simple and requires no arguments. It is run in the root directory of your Go module.
go mod tidy: Cleans up thego.modandgo.sumfiles by adding missing dependencies and removing unused ones.
bash
go mod tidy
Example
This example shows how go mod tidy updates your module files after you add or remove imports in your code.
go
package main import ( "fmt" "math/rand" ) func main() { fmt.Println("Random number:", rand.Intn(100)) }
Output
Random number: 42
Common Pitfalls
Common mistakes when using go mod tidy include:
- Running it outside the module root directory, which causes no effect.
- Not committing updated
go.modandgo.sumfiles after running it, leading to inconsistent builds. - Ignoring errors from
go mod tidythat indicate missing or incompatible dependencies.
bash
/* Wrong: Running outside module root */ $ cd some/other/folder $ go mod tidy /* Right: Run inside module root */ $ cd /path/to/your/module $ go mod tidy
Quick Reference
Summary tips for go mod tidy:
- Run it after adding or removing imports in your code.
- Always commit updated
go.modandgo.sumfiles. - Use it to keep dependencies clean and avoid bloated modules.
Key Takeaways
Run
go mod tidy in your module root to clean and update dependencies.It adds missing and removes unused dependencies from
go.mod and go.sum.Always commit changes to module files after running
go mod tidy.Avoid running it outside the module root directory to ensure it works correctly.