To use Go modules for dependency management, follow the steps below:
Initialize a new module in your project's root directory using the following command:
go mod init example.com/module
Replace example.com/module
with your module path. This will create a go.mod
file.
Import dependencies into your project using their import paths. For example:
import (
"fmt"
"github.com/go-sql-driver/mysql"
)
Run the command go build
or go test
in the root directory of your project. Go modules will automatically identify the packages used in your project and fetch the required dependencies.
If you want to explicitly add a dependency to your go.mod
file, you can use the following command:
go get <dependency-path>
Replace <dependency-path>
with the import path of the desired dependency.
To upgrade a dependency to the latest version, use the following command:
go get -u <dependency-path>
To remove a dependency from your go.mod
file, use the following command:
go mod tidy
If you want to explicitly specify a version of a dependency, you can use the following command:
go get <dependency-path>@<version>
Replace <version>
with the desired version tag, commit hash, or branch.
When sharing your project with others, it is recommended to commit both go.mod
and go.sum
files to version control, which allows exact versions of dependencies to be resolved consistently across different environments.
These are the basic steps to start using Go modules for dependency management in your project. Go modules offer more powerful features like semantic versioning and version constraints, which you can explore further if needed.