go.mod file is, how to create one, and how to manage dependencies with Go modules.
A directory becomes a Go module when it contains a valid go.mod file in its root. Use go mod init to create this file and record the module path.
Example: initialize a module
go.mod looks like:
- The file starts with a module declaration (
module <module-path>). - It commonly includes the minimum supported Go version (here
go 1.19).
Make sure the module path you choose is unique and, if you plan to publish the module, matches the repository location (for example
github.com/<org>/<repo>). Changing the module path later can be disruptive.main.go that imports a third-party package and uses it. Note the exported function name NewRandom() (capital R):
go mod tidy does
- Adds missing module requirements needed to build the module.
- Removes unused requirements.
- Updates
go.sumto match the resolved dependency graph. This keepsgo.modandgo.sumin sync with your source code.
go mod tidy:
go mod tidy, your go.mod will include resolved dependencies. Example:
Links and references
- Go Modules overview
github.com/pborman/uuid— package used in this example: https://github.com/pborman/uuid
- A directory is a Go module when it contains a valid
go.mod. go.modcontains the module declaration, the minimum Go version, and required module dependencies.- Use
go mod tidyfrequently to keepgo.modandgo.sumconsistent with your code. - The
replacedirective can be used ingo.modto override module versions or point to local copies during development.
Use
go mod tidy frequently during development to ensure go.mod and go.sum stay in sync with your source code.