“go mod” Command Examples

The “go mod” command in Go is used for module maintenance and managing dependencies in your project. It provides several commands to initialize, download, add, remove, verify, and vendor modules.

To initialize a new module in the current directory, you can use the “go mod init” command followed by the desired module name. For example, “go mod init mymodule” will initialize a new module named “mymodule” in the current directory. This will create a go.mod file that contains module-specific information.

The “go mod download” command is used to download modules and their dependencies into the local cache. This ensures that the required packages are available for your project, even when working offline.

The “go mod tidy” command adds any missing modules that are imported by your code and removes any unused modules from the go.mod file. This helps ensure that your project’s module dependencies are accurately reflected.

The “go mod verify” command verifies that the dependencies in your go.mod file have expected content. It checks if the downloaded packages match their cryptographic checksums, ensuring their integrity and security.

The “go mod vendor” command copies the source code of all module dependencies into the vendor directory of your project. This allows you to have a local copy of all dependencies, which can be useful in situations where you need to ensure reproducibility or build your project in an environment without internet access.

These “go mod” commands help in managing modules and their dependencies, making it easier to maintain and build your Go projects.

“go mod” Command Examples

1. Initialize new module in current directory:

# go mod init moduleName

2. Download modules to local cache:

# go mod download

3. Add missing and remove unused modules:

# go mod tidy

4. Verify dependencies have expected content:

# go mod verify

5. Copy sources of all dependencies into the vendor directory:

# go mod vendor

Summary

The “go mod” command in Go is used for module maintenance and dependency management. It allows you to initialize a new module, download module dependencies, add or remove modules, verify dependencies, and vendor modules. The “go mod init” command initializes a new module, “go mod download” downloads modules and their dependencies, “go mod tidy” adds missing modules and removes unused ones, “go mod verify” verifies the integrity of dependencies, and “go mod vendor” copies the source code of dependencies into the vendor directory. These commands help in managing modules and their dependencies effectively.

Related Post