How to Use go mod init to Initialize a Go Module
Use
go mod init <module-name> to create a new Go module in your project folder. This command initializes a go.mod file that tracks your module's dependencies and versioning.Syntax
The basic syntax of go mod init is:
go mod init <module-name>: Initializes a new module with the given name.
The module-name is usually the repository path or a unique name for your project.
bash
go mod init example.com/myproject
Example
This example shows how to create a new Go module named example.com/myapp. It creates a go.mod file that Go uses to manage dependencies.
bash
mkdir myapp cd myapp go mod init example.com/myapp cat go.mod
Output
module example.com/myapp
go 1.20
Common Pitfalls
Common mistakes when using go mod init include:
- Running
go mod initoutside your project folder. - Using an incorrect or missing module name.
- Not committing the generated
go.modfile to version control.
Always run the command inside your project root and choose a proper module path.
bash
cd .. go mod init # Error: no module name provided # Correct usage: go mod init example.com/myproject
Output
# Error: no module name provided
Quick Reference
| Command | Description |
|---|---|
| go mod init | Create a new go.mod file with the specified module name |
| go mod tidy | Add missing and remove unused dependencies |
| go build | Build your project using the module dependencies |
| go get | Add or update a dependency in go.mod |
Key Takeaways
Run
go mod init <module-name> inside your project folder to start a Go module.The
go.mod file tracks your module name and dependencies automatically.Choose a meaningful module name, usually your repository path.
Always commit the
go.mod file to version control to share dependencies.Use
go mod tidy to keep dependencies clean and updated.