How to use Go modules for dependency management?

To use Go modules for dependency management, follow the steps below:

  1. 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.

  2. Import dependencies into your project using their import paths. For example:

    import ( "fmt" "github.com/go-sql-driver/mysql" )
  3. 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.

  4. 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.

  5. To upgrade a dependency to the latest version, use the following command:

    go get -u <dependency-path>
  6. To remove a dependency from your go.mod file, use the following command:

    go mod tidy
  7. 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.

  8. 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.